refactor: extract shared useUrlParams hook and use push navigation for dialogs (#266)

* refactor: extract shared useUrlParams hook and use push navigation for dialogs

* Remove schedule badges and fix dialog safe area padding

* fix: deduplicate server health toasts with stable IDs

* fix: restore Enabled/Paused status badges on schedule jobs

* refactor: consolidate url state hooks and add shared test utilities
This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-07 13:02:56 -04:00
1 parent ec7a47dc10
commit 0d14e754e1
34 files changed
+1142 -423

No files matched your search

+2 -4
View File
@@ -31,7 +31,6 @@ import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib
import { getSwipeBackTarget } from '@/lib/navigation'
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useUIState } from '@/stores/uiStateStore'
const queryClient = new QueryClient({
defaultOptions: {
@@ -86,7 +85,7 @@ function AppShell() {
const navigate = useNavigate()
const location = useLocation()
const rootRef = useRef<HTMLDivElement>(null)
const { openSheet } = useMobileTabBar()
const { openSheet, open } = useMobileTabBar()
useTheme()
const swipeNav = useSwipeNavigation()
@@ -120,9 +119,8 @@ function AppShell() {
return /^\/repos\/[^/]+\/sessions\/[^/]+$/.test(location.pathname) && !openSheet
}
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
const { bind: bindMoreSwipe } = useRightEdgeSwipe(
() => setMoreDrawerOpen(true),
() => open('more'),
{
enabled: canOpenMoreWithSwipe(),
edgeWidth: 32,
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { DesktopSidebar } from './DesktopSidebar'
import * as useDesktopModule from '@/hooks/useDesktop'
@@ -13,8 +13,14 @@ vi.mock('@/hooks/useAuth')
function LocationDisplay() {
const location = useLocation()
const navigate = useNavigate()
return <div data-testid="location">{location.pathname}{location.search}</div>
return (
<div>
<div data-testid="location">{location.pathname}{location.search}</div>
<button onClick={() => navigate(-1)} data-testid="back-button">Back</button>
</div>
)
}
function createWrapper(initialEntries?: string[]) {
@@ -175,7 +181,7 @@ describe('DesktopSidebar', () => {
)
})
it('opens dialog items by updating the dialog query param', () => {
it('opens dialog items by updating the dialog query param (push) and closes on back', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
@@ -195,6 +201,10 @@ describe('DesktopSidebar', () => {
fireEvent.click(screen.getByText('Files'))
expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/abc?assistant=1&dialog=files')
fireEvent.click(screen.getByTestId('back-button'))
expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/abc?assistant=1')
})
it('opens settings by updating settings query params', () => {
@@ -216,6 +226,28 @@ describe('DesktopSidebar', () => {
fireEvent.click(screen.getByText('Settings'))
expect(screen.getByTestId('location').textContent).toBe('/?dialog=files&settings=open&tab=account')
expect(screen.getByTestId('location').textContent).toBe('/?dialog=files&settings=open&settingsTab=account')
})
it('preserves session route as return target when opening schedules', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(
<>
<DesktopSidebar />
<LocationDisplay />
</>,
{ wrapper: createWrapper(['/repos/5/sessions/abc?assistant=1']) }
)
fireEvent.click(screen.getByText('Schedules'))
expect(screen.getByTestId('location').textContent).toBe('/repos/5/schedules?returnTo=%2Frepos%2F5%2Fsessions%2Fabc%3Fassistant%3D1')
})
})
@@ -3,7 +3,9 @@ import { useLocation, useNavigate } from 'react-router-dom'
import { useDesktop } from '@/hooks/useDesktop'
import { useSidebarCollapsed } from '@/hooks/useSidebarCollapsed'
import { useAuth } from '@/hooks/useAuth'
import { useUrlParams } from '@/hooks/useUrlParams'
import { buildNavModel, type MoreDrawerItem, type NavPrimaryCta } from '@/components/navigation/moreDrawerItems'
import { getPathWithReturnTo } from '@/lib/navigation'
import { RepoQuickSwitchSheet } from '@/components/navigation/RepoQuickSwitchSheet'
import {
Sidebar,
@@ -16,6 +18,7 @@ import { FolderGit2 } from 'lucide-react'
export function DesktopSidebar() {
const location = useLocation()
const navigate = useNavigate()
const { updateParams } = useUrlParams()
const [collapsed, toggle] = useSidebarCollapsed()
const [repoSwitcherOpen, setRepoSwitcherOpen] = useState(false)
const { isAuthenticated, isLoading, logout } = useAuth()
@@ -46,19 +49,23 @@ export function DesktopSidebar() {
const handleItemClick = (item: MoreDrawerItem) => {
if (item.to) {
navigate(item.to)
const to = item.key === 'schedules'
? getPathWithReturnTo(item.to, `${location.pathname}${location.search}`)
: item.to
navigate(to)
} else if (item.dialog) {
const params = new URLSearchParams(location.search)
params.set('dialog', item.dialog)
params.delete('mobileTab')
navigate({ search: params.toString() }, { replace: true })
updateParams((p) => {
p.set('dialog', item.dialog!)
p.delete('mobileTab')
}, 'push')
} else if (item.key === 'logout') {
logout()
} else if (item.key === 'settings') {
const params = new URLSearchParams(location.search)
params.set('settings', 'open')
params.set('tab', 'account')
navigate({ search: params.toString() }, { replace: true })
updateParams((p) => {
p.set('settings', 'open')
p.set('settingsTab', 'account')
p.delete('mobileTab')
}, 'push')
} else if (item.key === 'repos') {
setRepoSwitcherOpen(true)
}
@@ -27,7 +27,6 @@ import { MemoryRouter } from 'react-router-dom'
import { MobileSheetHost } from './MobileSheetHost'
import { useMobile } from '@/hooks/useMobile'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { useUIState } from '@/stores/uiStateStore'
describe('MobileSheetHost', () => {
beforeEach(() => {
@@ -104,15 +103,18 @@ describe('MobileSheetHost', () => {
expect(screen.getByTestId('notifications-sheet')).toBeInTheDocument()
})
it('renders MoreDrawer when isMoreDrawerOpen is true', () => {
useUIState.setState({ isMoreDrawerOpen: true })
it('renders MoreDrawer when mobileTab=more', () => {
vi.mocked(useMobileTabBar).mockReturnValue({
openSheet: 'more',
open: vi.fn(),
close: vi.fn(),
})
render(
<MemoryRouter initialEntries={['/']}>
<MemoryRouter initialEntries={['/?mobileTab=more']}>
<MobileSheetHost />
</MemoryRouter>,
)
expect(screen.getByTestId('more-drawer')).toBeInTheDocument()
useUIState.setState({ isMoreDrawerOpen: false })
})
it('closes sheet when onClose is called', () => {
@@ -4,13 +4,10 @@ import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { RepoQuickSwitchSheet } from '@/components/navigation/RepoQuickSwitchSheet'
import { NotificationsSheet } from '@/components/navigation/NotificationsSheet'
import { MoreDrawer } from '@/components/navigation/MoreDrawer'
import { useUIState } from '@/stores/uiStateStore'
export function MobileSheetHost() {
const isMobile = useMobile()
const { openSheet, close } = useMobileTabBar()
const isMoreDrawerOpen = useUIState((state) => state.isMoreDrawerOpen)
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
if (!isMobile) return null
@@ -27,7 +24,7 @@ export function MobileSheetHost() {
/>
)}
{openSheet === 'notifications' && <NotificationsSheet isOpen onClose={close} />}
<MoreDrawer isOpen={isMoreDrawerOpen} onClose={() => setMoreDrawerOpen(false)} />
<MoreDrawer isOpen={openSheet === 'more'} onClose={close} />
</>
)
}
@@ -4,8 +4,8 @@ import { FolderGit2, FolderOpen, CalendarClock, Menu, Info, History, Bot } from
import { cn } from '@/lib/utils'
import { useMobile } from '@/hooks/useMobile'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { useUrlParams } from '@/hooks/useUrlParams'
import { useScheduleUrlState, type ScheduleTab } from '@/hooks/useScheduleUrlState'
import { useUIState } from '@/stores/uiStateStore'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
interface TabDef {
@@ -19,15 +19,13 @@ interface TabDef {
interface GlobalTabsArgs {
pathname: string
search: string
openSheet: ReturnType<typeof useMobileTabBar>['openSheet']
open: ReturnType<typeof useMobileTabBar>['open']
close: ReturnType<typeof useMobileTabBar>['close']
navigate: ReturnType<typeof useNavigate>
isInsideRepo: boolean
repoId: string | null
isMoreDrawerOpen: boolean
setMoreDrawerOpen: (open: boolean) => void
updateParams: ReturnType<typeof useUrlParams>['updateParams']
}
type TabBarMode = 'hidden' | 'global' | 'schedule'
@@ -65,17 +63,10 @@ function getMobileTabRouteState(pathname: string): MobileTabRouteState {
}
}
function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, isInsideRepo, repoId, isMoreDrawerOpen, setMoreDrawerOpen }: GlobalTabsArgs): TabDef[] {
const navigateWithSearch = (params: URLSearchParams) => {
const nextSearch = params.toString()
navigate(nextSearch ? `${pathname}?${nextSearch}` : pathname, { replace: true })
}
function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideRepo, repoId, updateParams }: GlobalTabsArgs): TabDef[] {
const handleFilesClick = () => {
if (isInsideRepo && repoId) {
const newParams = new URLSearchParams(search)
newParams.set('dialog', 'files')
navigateWithSearch(newParams)
updateParams((p) => { p.set('dialog', 'files'); p.delete('mobileTab') }, 'push')
} else {
open('files')
}
@@ -119,8 +110,8 @@ function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, i
key: 'more',
label: 'More',
icon: Menu,
onClick: () => setMoreDrawerOpen(true),
active: isMoreDrawerOpen,
onClick: () => open('more'),
active: openSheet === 'more',
},
]
}
@@ -187,13 +178,12 @@ const TabBarRow = memo(function TabBarRow({ tabs }: TabBarRowProps) {
})
export const MobileTabBar = memo(function MobileTabBar() {
const { pathname, search } = useLocation()
const { pathname } = useLocation()
const navigate = useNavigate()
const { openSheet, open, close } = useMobileTabBar()
const { updateParams } = useUrlParams()
const { scheduleTab, setScheduleTab } = useScheduleUrlState()
const isMobile = useMobile()
const isMoreDrawerOpen = useUIState((state) => state.isMoreDrawerOpen)
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
const routeState = useMemo(() => getMobileTabRouteState(pathname), [pathname])
const tabs = useMemo<TabDef[]>(
@@ -201,28 +191,24 @@ export const MobileTabBar = memo(function MobileTabBar() {
? buildScheduleTabs(scheduleTab, setScheduleTab)
: buildGlobalTabs({
pathname,
search,
openSheet,
open,
close,
navigate,
isInsideRepo: routeState.isInsideRepo,
repoId: routeState.repoId,
isMoreDrawerOpen,
setMoreDrawerOpen,
updateParams,
})),
[
routeState,
scheduleTab,
setScheduleTab,
pathname,
search,
openSheet,
open,
close,
navigate,
isMoreDrawerOpen,
setMoreDrawerOpen,
updateParams,
],
)
@@ -162,7 +162,7 @@ describe('MoreDrawer', () => {
renderMoreDrawer({ onClose: handleClose })
fireEvent.click(screen.getByText('Settings'))
expect(navigateMock).toHaveBeenCalledWith(
{ search: 'settings=open&tab=account' },
{ search: 'settings=open&settingsTab=account' },
{ replace: true },
)
})
@@ -250,4 +250,16 @@ describe('MoreDrawer', () => {
expect(screen.queryByText('wrong-repo')).not.toBeInTheDocument()
})
it('preserves session route as return target when opening schedules', () => {
const navigateMock = vi.fn()
vi.mocked(useNavigate).mockReturnValue(navigateMock)
mockAuth()
mockServerHealth()
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1?assistant=1', routePath: '/repos/:id/sessions/:sessionId' })
fireEvent.click(screen.getByText('Schedules'))
expect(navigateMock).toHaveBeenCalledWith('/repos/1/schedules?returnTo=%2Frepos%2F1%2Fsessions%2Fsession-1%3Fassistant%3D1')
})
})
@@ -4,6 +4,7 @@ import { ChevronDown, ChevronRight, Command as CommandIcon, FileText, X, GitBran
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useCommands } from '@/hooks/useCommands'
import { useUrlParams } from '@/hooks/useUrlParams'
import { useUIState } from '@/stores/uiStateStore'
import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
@@ -13,7 +14,7 @@ import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { buildMoreItems } from './moreDrawerItems'
import { useSwipeBack } from '@/hooks/useMobile'
import { getRepoDisplayName } from '@/lib/utils'
import { isAssistantPath } from '@/lib/navigation'
import { getPathWithReturnTo, isAssistantPath } from '@/lib/navigation'
import type { components } from '@/api/opencode-types'
type CommandType = components['schemas']['Command']
@@ -31,13 +32,13 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const [commandsOpen, setCommandsOpen] = useState(false)
const [mentionFileBrowserOpen, setMentionFileBrowserOpen] = useState(false)
const swipeRef = useRef<HTMLDivElement>(null)
const skipHistoryBackOnCloseRef = useRef(false)
const { bind } = useSwipeBack(onClose, { enabled: isOpen, suspendsRouteSwipe: true })
const { searchParams, updateParams } = useUrlParams()
const { logout } = useAuth()
const { data: health } = useServerHealth()
const isSessionDetail = /^\/repos\/\d+\/sessions\/[^/]+$/.test(location.pathname)
const isAssistantRoute = isAssistantPath(location.pathname)
const isAssistantSession = isSessionDetail && new URLSearchParams(location.search).get('assistant') === '1'
const isAssistantSession = isSessionDetail && searchParams.get('assistant') === '1'
const { filterCommands } = useCommands(isSessionDetail ? OPENCODE_API_ENDPOINT : null)
const activePromptFileBasePath = useUIState((state) => state.activePromptFileBasePath)
const selectPromptCommand = useUIState((state) => state.selectPromptCommand)
@@ -50,37 +51,6 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
}
}, [isOpen, bind])
const onCloseRef = useRef(onClose)
useEffect(() => {
onCloseRef.current = onClose
}, [onClose])
useEffect(() => {
if (!isOpen) return
skipHistoryBackOnCloseRef.current = false
let sentinelActive = true
const baseState = window.history.state
const baseUrl = window.location.href
window.history.pushState({ ...(baseState ?? {}), moreDrawerSentinel: true }, '', baseUrl)
const onPop = () => {
if (!sentinelActive) return
sentinelActive = false
onCloseRef.current()
}
window.addEventListener('popstate', onPop)
return () => {
window.removeEventListener('popstate', onPop)
// Only go back if sentinel is still active AND we haven't navigated away
if (sentinelActive && !skipHistoryBackOnCloseRef.current) {
sentinelActive = false
const top = window.history.state as { moreDrawerSentinel?: boolean } | null
if (top?.moreDrawerSentinel && window.location.href === baseUrl) {
window.history.back()
}
}
}
}, [isOpen])
const { data: repo } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => repoId ? getRepo(repoId) : null,
@@ -93,13 +63,11 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
: repo ? getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath) : null
const handleSettingsClick = () => {
const newParams = new URLSearchParams(location.search)
newParams.delete('mobileTab')
newParams.set('settings', 'open')
newParams.set('tab', 'account')
skipHistoryBackOnCloseRef.current = true
navigate({ search: newParams.toString() }, { replace: true })
onClose()
updateParams((p) => {
p.delete('mobileTab')
p.set('settings', 'open')
p.set('settingsTab', 'account')
}, 'replace')
}
const handleLogoutClick = async () => {
@@ -112,16 +80,16 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const handleItemClick = (item: ReturnType<typeof buildMoreItems>[0]) => {
if (item.to) {
skipHistoryBackOnCloseRef.current = true
navigate(item.to)
const to = item.key === 'schedules'
? getPathWithReturnTo(item.to, `${location.pathname}${location.search}`)
: item.to
navigate(to)
} else if (item.dialog) {
const newParams = new URLSearchParams(location.search)
newParams.set('dialog', item.dialog)
newParams.delete('mobileTab')
skipHistoryBackOnCloseRef.current = true
navigate({ search: newParams.toString() }, { replace: true })
updateParams((p) => {
p.set('dialog', item.dialog!)
p.delete('mobileTab')
}, 'replace')
}
onClose()
}
const handleCommandClick = (command: CommandType) => {
@@ -9,6 +9,7 @@ import { listRepos } from '@/api/repos'
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
import { FolderGit2, Check, Plus, House } from 'lucide-react'
import { isAssistantPath, getAssistantPath } from '@/lib/navigation'
import { useUrlParams } from '@/hooks/useUrlParams'
interface RepoQuickSwitchSheetProps {
isOpen: boolean
@@ -18,6 +19,7 @@ interface RepoQuickSwitchSheetProps {
export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetProps) {
const navigate = useNavigate()
const location = useLocation()
const { searchParams } = useUrlParams()
const [searchQuery, setSearchQuery] = useState('')
const [addRepoOpen, setAddRepoOpen] = useState(false)
@@ -45,7 +47,7 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
)
}, [repos, searchQuery])
const isUrlControlledSheet = new URLSearchParams(location.search).get('mobileTab') === 'repos'
const isUrlControlledSheet = searchParams.get('mobileTab') === 'repos'
const navigateAndClose = (path: string, options?: { replace?: boolean }) => {
navigate(path, options)
@@ -55,7 +57,7 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
}
const handleClick = (id: number) => {
const pendingAction = new URLSearchParams(location.search).get('mobileTabAction')
const pendingAction = searchParams.get('mobileTabAction')
if (isAssistantRoute) {
navigateAndClose(`/repos/${id}`, { replace: true })
@@ -1,15 +1,15 @@
import { MoreVertical } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useUIState } from '@/stores/uiStateStore'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
export function SessionMoreButton() {
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
const { open } = useMobileTabBar()
return (
<Button
variant="outline"
size="sm"
onClick={() => setMoreDrawerOpen(true)}
onClick={() => open('more')}
className="md:hidden h-10 w-10 p-0 text-foreground border-border hover:bg-accent"
aria-label="More"
>
@@ -260,9 +260,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
overlayClassName="bg-black/80"
className="flex h-dvh max-h-dvh w-full max-w-4xl flex-col gap-0 overflow-hidden border-border bg-background p-0 shadow-lg sm:h-[min(85vh,760px)] sm:max-h-[85vh] sm:w-[calc(100vw-1rem)]"
mobileFullscreen
className="flex h-dvh max-h-dvh w-full max-w-4xl flex-col gap-0 overflow-hidden border-border bg-background p-0 shadow-lg sm:h-[min(85vh,760px)] sm:max-h-[85vh] sm:max-w-[90vw] sm:w-[calc(100vw-1rem)]"
>
<DialogHeader className="shrink-0 space-y-1 px-3 sm:px-6 pt-6 pb-3 pr-14">
<DialogHeader className="shrink-0 space-y-1 border-b border-border px-3 sm:px-6 py-4">
<DialogTitle>{job ? 'Edit schedule' : 'New schedule'}</DialogTitle>
<DialogDescription className="mt-0">
Create a reusable repo job with a visual schedule builder, manual runs, and optional advanced metadata.
@@ -62,7 +62,7 @@ describe('SettingsDialog', () => {
return (
<>
<button onClick={() => navigate('?settings=open&tab=general')}>Open Settings</button>
<button onClick={() => navigate('?settings=open&settingsTab=general')}>Open Settings</button>
<button onClick={() => navigate('/')}>Close Settings</button>
{isOpen && <span data-testid="dialog-open">Dialog Open</span>}
<SettingsDialog />
@@ -1,46 +1,13 @@
import { useEffect } from 'react'
import { renderHook, act } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { act, render, screen } from '@testing-library/react'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { describe, it, expect } from 'vitest'
import { useScheduleUrlState } from '../useScheduleUrlState'
/**
* Captures the current location.search into a ref for test assertions.
* Must be rendered inside a <MemoryRouter>.
*/
function LocationCatcher({ capturedSearch }: { capturedSearch: { current: string } }) {
const location = useLocation()
useEffect(() => {
capturedSearch.current = location.search
})
return null
}
/**
* Creates a wrapper that captures the current location.search into a ref
* so tests can verify URL param changes after actions.
*/
function createWrapper(initialEntries: string[], capturedSearch: { current: string }) {
return function Wrapper({ children }: { children: React.ReactNode }) {
return (
<MemoryRouter initialEntries={initialEntries}>
<LocationCatcher capturedSearch={capturedSearch} />
{children}
</MemoryRouter>
)
}
}
function renderScheduleUrlState(initialEntries = ['/']) {
const capturedSearch: { current: string } = { current: '' }
const wrapper = createWrapper(initialEntries, capturedSearch)
const rendered = renderHook(() => useScheduleUrlState(), { wrapper })
return { ...rendered, capturedSearch }
}
import { renderHookWithRouterAndLocation } from '@/test/test-utils'
describe('useScheduleUrlState', () => {
it('defaults to jobs tab, null dialog, and null ids when URL is empty', () => {
const { result } = renderScheduleUrlState()
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState())
expect(result.current.scheduleTab).toBe('jobs')
expect(result.current.dialog).toBeNull()
expect(result.current.jobId).toBeNull()
@@ -49,7 +16,7 @@ describe('useScheduleUrlState', () => {
})
it('setScheduleTab updates tab and removes param when set to jobs', () => {
const { result } = renderScheduleUrlState()
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState())
act(() => {
result.current.setScheduleTab('prompts')
})
@@ -62,7 +29,7 @@ describe('useScheduleUrlState', () => {
})
it('openEditJob sets dialog to edit and sets jobId', () => {
const { result, capturedSearch } = renderScheduleUrlState()
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
act(() => {
result.current.openEditJob(12)
})
@@ -74,7 +41,7 @@ describe('useScheduleUrlState', () => {
})
it('openDeleteTemplate sets promptDialog to delete and sets templateId', () => {
const { result } = renderScheduleUrlState()
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
act(() => {
result.current.openDeleteTemplate(5)
})
@@ -84,7 +51,7 @@ describe('useScheduleUrlState', () => {
})
it('openImportTemplate sets promptDialog to import and clears templateId', () => {
const { result } = renderScheduleUrlState(['/?templateId=3&jobId=7'])
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?templateId=3&jobId=7'])
act(() => {
result.current.openImportTemplate()
})
@@ -94,7 +61,7 @@ describe('useScheduleUrlState', () => {
})
it('closeDialog after edit preserves scheduleDialog and jobId', () => {
const { result, capturedSearch } = renderScheduleUrlState()
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
act(() => {
result.current.openEditJob(12)
})
@@ -112,7 +79,7 @@ describe('useScheduleUrlState', () => {
})
it('closeDialog after delete preserves jobId when canceling', () => {
const { result, capturedSearch } = renderScheduleUrlState()
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
act(() => {
result.current.openDeleteJob(42)
})
@@ -129,7 +96,7 @@ describe('useScheduleUrlState', () => {
})
it('closePromptDialog after openNewTemplate clears promptDialog and templateId', () => {
const { result } = renderScheduleUrlState()
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
// Open new template
act(() => {
result.current.openNewTemplate()
@@ -146,13 +113,13 @@ describe('useScheduleUrlState', () => {
})
it('parses jobId=abc as null (NaN) and runId=44 as 44', () => {
const { result } = renderScheduleUrlState(['/?jobId=abc&runId=44'])
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?jobId=abc&runId=44'])
expect(result.current.jobId).toBeNull()
expect(result.current.runId).toBe(44)
})
it('preserves unrelated params across setScheduleTab and openEditJob and closeDialog', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?assistant=1'])
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?assistant=1'])
// setScheduleTab preserves assistant param
act(() => {
@@ -177,7 +144,7 @@ describe('useScheduleUrlState', () => {
})
it('openNewJob sets dialog to new and clears jobId and templateId', () => {
const { result } = renderScheduleUrlState(['/?templateId=2&jobId=5'])
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?templateId=2&jobId=5'])
act(() => {
result.current.openNewJob()
})
@@ -187,7 +154,7 @@ describe('useScheduleUrlState', () => {
})
it('openDeleteJob sets dialog to delete and sets jobId', () => {
const { result } = renderScheduleUrlState()
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
act(() => {
result.current.openDeleteJob(42)
})
@@ -197,7 +164,7 @@ describe('useScheduleUrlState', () => {
})
it('openEditTemplate sets promptDialog to edit and sets templateId', () => {
const { result } = renderScheduleUrlState()
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
act(() => {
result.current.openEditTemplate(99)
})
@@ -207,7 +174,7 @@ describe('useScheduleUrlState', () => {
})
it('selectRun sets and clears runId', () => {
const { result } = renderScheduleUrlState()
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
act(() => {
result.current.selectRun(20)
})
@@ -220,32 +187,32 @@ describe('useScheduleUrlState', () => {
})
it('reads valid scheduleTab from URL', () => {
const { result } = renderScheduleUrlState(['/?scheduleTab=detail'])
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?scheduleTab=detail'])
expect(result.current.scheduleTab).toBe('detail')
})
it('reads valid scheduleDialog from URL', () => {
const { result } = renderScheduleUrlState(['/?scheduleDialog=edit'])
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?scheduleDialog=edit'])
expect(result.current.dialog).toBe('edit')
})
it('reads valid promptDialog from URL', () => {
const { result } = renderScheduleUrlState(['/?promptDialog=import'])
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?promptDialog=import'])
expect(result.current.promptDialog).toBe('import')
})
it('resolves invalid tab values to jobs', () => {
const { result } = renderScheduleUrlState(['/?scheduleTab=invalid'])
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?scheduleTab=invalid'])
expect(result.current.scheduleTab).toBe('jobs')
})
it('resolves invalid dialog values to null', () => {
const { result } = renderScheduleUrlState(['/?scheduleDialog=invalid'])
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?scheduleDialog=invalid'])
expect(result.current.dialog).toBeNull()
})
it('closeDialog for new dialog does not affect jobId', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?scheduleDialog=new&jobId=7'])
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?scheduleDialog=new&jobId=7'])
expect(result.current.dialog).toBe('new')
expect(result.current.jobId).toBe(7)
@@ -259,7 +226,7 @@ describe('useScheduleUrlState', () => {
})
it('closePromptDialog for import clears promptDialog but preserves jobId', () => {
const { result } = renderScheduleUrlState(['/?jobId=7&promptDialog=import'])
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?jobId=7&promptDialog=import'])
act(() => {
result.current.closePromptDialog()
})
@@ -269,7 +236,7 @@ describe('useScheduleUrlState', () => {
})
it('returns stable function references across rerenders', () => {
const { result, rerender } = renderScheduleUrlState()
const { result, rerender } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
const firstSetScheduleTab = result.current.setScheduleTab
const firstOpenEditJob = result.current.openEditJob
const firstCloseDialog = result.current.closeDialog
@@ -291,7 +258,7 @@ describe('useScheduleUrlState', () => {
describe('combined atomic URL mutations', () => {
it('selectJobAndView sets jobId and scheduleTab in a single navigation', () => {
const { result, capturedSearch } = renderScheduleUrlState()
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
act(() => {
result.current.selectJobAndView(42)
})
@@ -302,7 +269,7 @@ describe('useScheduleUrlState', () => {
})
it('selectJobAndView preserves unrelated params', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?assistant=1'])
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?assistant=1'])
act(() => {
result.current.selectJobAndView(99)
})
@@ -312,7 +279,7 @@ describe('useScheduleUrlState', () => {
})
it('selectJobAndCloseDialog sets jobId and removes scheduleDialog', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?scheduleDialog=new'])
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?scheduleDialog=new'])
act(() => {
result.current.selectJobAndCloseDialog(7)
})
@@ -323,7 +290,7 @@ describe('useScheduleUrlState', () => {
})
it('selectJobAndCloseDialog from edit preserves jobId and removes dialog', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?scheduleDialog=edit&jobId=3'])
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?scheduleDialog=edit&jobId=3'])
act(() => {
result.current.selectJobAndCloseDialog(3)
})
@@ -334,7 +301,7 @@ describe('useScheduleUrlState', () => {
})
it('selectJobAndCloseDialog preserves unrelated params', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?scheduleDialog=edit&assistant=1'])
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?scheduleDialog=edit&assistant=1'])
act(() => {
result.current.selectJobAndCloseDialog(5)
})
@@ -344,7 +311,7 @@ describe('useScheduleUrlState', () => {
})
it('replaceUrlParams can set and delete multiple params atomically', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?foo=1&bar=2'])
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?foo=1&bar=2'])
act(() => {
result.current.replaceUrlParams((p) => {
p.set('jobId', '10')
@@ -361,7 +328,7 @@ describe('useScheduleUrlState', () => {
})
it('replaceUrlParams preserves all params when no modifications are made', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?jobId=5&scheduleTab=detail'])
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), ['/?jobId=5&scheduleTab=detail'])
act(() => {
result.current.replaceUrlParams((_p) => {
// No modifications
@@ -373,4 +340,107 @@ describe('useScheduleUrlState', () => {
expect(capturedSearch.current).toContain('scheduleTab=detail')
})
})
describe('push/replace history mode', () => {
it('openNewJob uses push so navigate(-1) closes the dialog', () => {
function PushHarness() {
const { dialog, openNewJob } = useScheduleUrlState()
const navigate = useNavigate()
const [step, setStep] = useState<'start' | 'opened' | 'back'>('start')
const handled = useRef(false)
useEffect(() => {
if (handled.current) return
if (step === 'opened') {
handled.current = true
openNewJob()
} else if (step === 'back') {
handled.current = true
navigate(-1)
}
}, [step, openNewJob, navigate])
return (
<div>
<span data-testid="dialog">{dialog ?? 'null'}</span>
<button onClick={() => { handled.current = false; setStep('opened') }}>
open
</button>
<button onClick={() => { handled.current = false; setStep('back') }}>
back
</button>
</div>
)
}
render(
<MemoryRouter initialEntries={['/other', '/']}>
<PushHarness />
</MemoryRouter>,
)
expect(screen.getByTestId('dialog').textContent).toBe('null')
act(() => { screen.getByText('open').click() })
expect(screen.getByTestId('dialog').textContent).toBe('new')
act(() => { screen.getByText('back').click() })
expect(screen.getByTestId('dialog').textContent).toBe('null')
})
it('setScheduleTab uses replace so navigate(-1) does not step through tab changes', () => {
function ReplaceHarness() {
const { scheduleTab, setScheduleTab } = useScheduleUrlState()
const navigate = useNavigate()
const [step, setStep] = useState<'start' | 'switched' | 'back'>('start')
const handled = useRef(false)
useEffect(() => {
if (handled.current) return
if (step === 'switched') {
handled.current = true
setScheduleTab('runs')
} else if (step === 'back') {
handled.current = true
navigate(-1)
}
}, [step, setScheduleTab, navigate])
return (
<div>
<span data-testid="scheduleTab">{scheduleTab}</span>
<button onClick={() => { handled.current = false; setStep('switched') }}>
switch
</button>
<button onClick={() => { handled.current = false; setStep('back') }}>
back
</button>
</div>
)
}
render(
<MemoryRouter initialEntries={['/other', '/']}>
<ReplaceHarness />
</MemoryRouter>,
)
expect(screen.getByTestId('scheduleTab').textContent).toBe('jobs')
act(() => { screen.getByText('switch').click() })
expect(screen.getByTestId('scheduleTab').textContent).toBe('runs')
act(() => { screen.getByText('back').click() })
expect(screen.getByTestId('scheduleTab').textContent).toBe('jobs')
})
it('openEditTemplate(7) sets promptDialog=edit and templateId=7', () => {
const { result } = renderHookWithRouterAndLocation(() => useScheduleUrlState(), )
act(() => {
result.current.openEditTemplate(7)
})
expect(result.current.promptDialog).toBe('edit')
expect(result.current.templateId).toBe(7)
})
})
})
+49 -2
View File
@@ -1,5 +1,6 @@
import { renderHook, act } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { renderHook, act, render, screen } from '@testing-library/react'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { useDialogParam } from './useDialogParam'
import { describe, it, expect } from 'vitest'
@@ -67,4 +68,50 @@ describe('useDialogParam', () => {
expect(result1.current[0]).toBe(true)
expect(result2.current[0]).toBe(false)
})
it('open pushes so browser back closes the dialog', () => {
function DialogPushHarness() {
const [isOpen, setOpen] = useDialogParam('test')
const navigate = useNavigate()
const [step, setStep] = useState<'start' | 'opened' | 'back'>('start')
const handled = useRef(false)
useEffect(() => {
if (handled.current) return
if (step === 'opened') {
handled.current = true
setOpen(true)
} else if (step === 'back') {
handled.current = true
navigate(-1)
}
}, [step, setOpen, navigate])
return (
<div>
<span data-testid="dialog-state">{isOpen ? 'open' : 'closed'}</span>
<button onClick={() => { handled.current = false; setStep('opened') }}>
open
</button>
<button onClick={() => { handled.current = false; setStep('back') }}>
back
</button>
</div>
)
}
render(
<MemoryRouter initialEntries={['/']}>
<DialogPushHarness />
</MemoryRouter>,
)
expect(screen.getByTestId('dialog-state').textContent).toBe('closed')
act(() => { screen.getByText('open').click() })
expect(screen.getByTestId('dialog-state').textContent).toBe('open')
act(() => { screen.getByText('back').click() })
expect(screen.getByTestId('dialog-state').textContent).toBe('closed')
})
})
+17 -20
View File
@@ -1,27 +1,24 @@
import { useCallback, useEffect, useRef } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useCallback } from 'react'
import { useUrlParams } from './useUrlParams'
export function useDialogParam(name: string): [boolean, (open: boolean) => void] {
const navigate = useNavigate()
const location = useLocation()
const searchRef = useRef(location.search)
const { searchParams, updateParams } = useUrlParams()
useEffect(() => {
searchRef.current = location.search
}, [location.search])
const isOpen = searchParams.get('dialog') === name
const isOpen = new URLSearchParams(location.search).get('dialog') === name
const setOpen = useCallback((open: boolean) => {
const p = new URLSearchParams(searchRef.current)
if (open) {
p.set('dialog', name)
p.delete('mobileTab')
} else if (p.get('dialog') === name) {
p.delete('dialog')
}
navigate({ search: p.toString() }, { replace: true })
}, [navigate, name])
const setOpen = useCallback(
(open: boolean) => {
updateParams((p) => {
if (open) {
p.set('dialog', name)
p.delete('mobileTab')
} else if (p.get('dialog') === name) {
p.delete('dialog')
}
}, open ? 'push' : 'replace')
},
[updateParams, name],
)
return [isOpen, setOpen]
}
+58 -43
View File
@@ -1,16 +1,9 @@
import { renderHook, act } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { renderHook, act, render, screen } from '@testing-library/react'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { describe, it, expect } from 'vitest'
import { useMobileTabBar, type MobileSheetKey } from './useMobileTabBar'
function renderHookWithRouter<T>(renderFn: () => T) {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<MemoryRouter initialEntries={['/']}>
{children}
</MemoryRouter>
)
return renderHook(renderFn, { wrapper })
}
import { useMobileTabBar } from './useMobileTabBar'
import { renderHookWithRouter, createRouterWrapper } from '@/test/test-utils'
describe('useMobileTabBar', () => {
it('returns null for openSheet when no mobileTab param is present', () => {
@@ -20,11 +13,7 @@ describe('useMobileTabBar', () => {
it('returns the correct openSheet when mobileTab param is set', () => {
const { result } = renderHook(() => useMobileTabBar(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/?mobileTab=repos']}>
{children}
</MemoryRouter>
),
wrapper: createRouterWrapper(['/?mobileTab=repos']),
})
expect(result.current.openSheet).toBe('repos')
})
@@ -39,11 +28,7 @@ describe('useMobileTabBar', () => {
it('close removes the mobileTab param', () => {
const { result } = renderHook(() => useMobileTabBar(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/?mobileTab=notifications']}>
{children}
</MemoryRouter>
),
wrapper: createRouterWrapper(['/?mobileTab=notifications']),
})
expect(result.current.openSheet).toBe('notifications')
act(() => {
@@ -54,24 +39,16 @@ describe('useMobileTabBar', () => {
it('resolves invalid values to null', () => {
const { result } = renderHook(() => useMobileTabBar(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/?mobileTab=invalid']}>
{children}
</MemoryRouter>
),
wrapper: createRouterWrapper(['/?mobileTab=invalid']),
})
expect(result.current.openSheet).toBeNull()
})
it('handles all valid MobileSheetKey values', () => {
const validKeys: MobileSheetKey[] = ['repos', 'files', 'notifications', 'more']
const validKeys = ['repos', 'files', 'notifications', 'more'] as const
validKeys.forEach((key) => {
const { result } = renderHook(() => useMobileTabBar(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={[`/?mobileTab=${key}`]}>
{children}
</MemoryRouter>
),
wrapper: createRouterWrapper([`/?mobileTab=${key}`]),
})
expect(result.current.openSheet).toBe(key)
})
@@ -79,11 +56,7 @@ describe('useMobileTabBar', () => {
it('returns stable openSheet identity across rerenders when search is unchanged', () => {
const { result, rerender } = renderHook(() => useMobileTabBar(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/?mobileTab=repos']}>
{children}
</MemoryRouter>
),
wrapper: createRouterWrapper(['/?mobileTab=repos']),
})
const firstOpenSheet = result.current.openSheet
rerender()
@@ -101,14 +74,56 @@ describe('useMobileTabBar', () => {
it('open callback identity is stable across location.search changes', () => {
const { result, rerender } = renderHook(() => useMobileTabBar(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/?foo=1']}>
{children}
</MemoryRouter>
),
wrapper: createRouterWrapper(['/?foo=1']),
})
const firstOpen = result.current.open
rerender()
expect(result.current.open).toBe(firstOpen)
})
it('open (push) then navigate(-1) sets openSheet to null', () => {
function Harness() {
const { openSheet, open } = useMobileTabBar()
const navigate = useNavigate()
const [step, setStep] = useState<'start' | 'pushed' | 'back'>('start')
const handled = useRef(false)
useEffect(() => {
if (handled.current) return
if (step === 'pushed') {
handled.current = true
open('files')
} else if (step === 'back') {
handled.current = true
navigate(-1)
}
}, [step, open, navigate])
return (
<div>
<span data-testid="openSheet">{openSheet}</span>
<button onClick={() => { handled.current = false; setStep('pushed') }}>
open
</button>
<button onClick={() => { handled.current = false; setStep('back') }}>
back
</button>
</div>
)
}
render(
<MemoryRouter initialEntries={['/']}>
<Harness />
</MemoryRouter>,
)
expect(screen.getByTestId('openSheet').textContent).toBe('')
act(() => { screen.getByText('open').click() })
expect(screen.getByTestId('openSheet').textContent).toBe('files')
act(() => { screen.getByText('back').click() })
expect(screen.getByTestId('openSheet').textContent).toBe('')
})
})
+13 -30
View File
@@ -1,46 +1,29 @@
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useCallback, useMemo } from 'react'
import { useUrlParams } from './useUrlParams'
export type MobileSheetKey = 'repos' | 'files' | 'notifications' | 'more'
type MobileSheetKey = 'repos' | 'files' | 'notifications' | 'more'
export interface UseMobileTabBarReturn {
interface UseMobileTabBarReturn {
openSheet: MobileSheetKey | null
open: (key: MobileSheetKey) => void
close: () => void
}
export function useMobileTabBar(): UseMobileTabBarReturn {
const navigate = useNavigate()
const location = useLocation()
const searchRef = useRef(location.search)
useEffect(() => {
searchRef.current = location.search
}, [location.search])
const { searchParams, updateParams } = useUrlParams()
const openSheet = useMemo<MobileSheetKey | null>(() => {
const searchParams = new URLSearchParams(location.search)
const mobileTabParam = searchParams.get('mobileTab')
return (mobileTabParam === 'repos' || mobileTabParam === 'files' || mobileTabParam === 'notifications' || mobileTabParam === 'more')
? mobileTabParam
: null
}, [location.search])
const v = searchParams.get('mobileTab')
return (v === 'repos' || v === 'files' || v === 'notifications' || v === 'more') ? v : null
}, [searchParams])
const open = useCallback((key: MobileSheetKey) => {
const newParams = new URLSearchParams(searchRef.current)
newParams.set('mobileTab', key)
navigate({ search: newParams.toString() }, { replace: true })
}, [navigate])
updateParams((p) => p.set('mobileTab', key), 'push')
}, [updateParams])
const close = useCallback(() => {
const newParams = new URLSearchParams(searchRef.current)
newParams.delete('mobileTab')
navigate({ search: newParams.toString() }, { replace: true })
}, [navigate])
updateParams((p) => p.delete('mobileTab'), 'replace')
}, [updateParams])
return {
openSheet,
open,
close,
}
return { openSheet, open, close }
}
+41 -58
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useCallback, useMemo } from 'react'
import { useUrlParams } from './useUrlParams'
export type ScheduleTab = 'jobs' | 'detail' | 'runs' | 'prompts'
export type ScheduleDialog = 'new' | 'edit' | 'delete' | null
@@ -35,15 +35,7 @@ function parseNullableInt(value: string | null): number | null {
}
export function useScheduleUrlState(): UseScheduleUrlStateReturn {
const navigate = useNavigate()
const location = useLocation()
const searchRef = useRef(location.search)
useEffect(() => {
searchRef.current = location.search
}, [location.search])
const searchParams = useMemo(() => new URLSearchParams(location.search), [location.search])
const { searchParams, updateParams } = useUrlParams()
const scheduleTab = useMemo<ScheduleTab>(() => {
const tabParam = searchParams.get('scheduleTab')
@@ -73,11 +65,30 @@ export function useScheduleUrlState(): UseScheduleUrlStateReturn {
const runId = useMemo<number | null>(() => parseNullableInt(searchParams.get('runId')), [searchParams])
const templateId = useMemo<number | null>(() => parseNullableInt(searchParams.get('templateId')), [searchParams])
const replaceUrlParams = useCallback((updater: (params: URLSearchParams) => void) => {
const p = new URLSearchParams(searchRef.current)
updater(p)
navigate({ search: p.toString() }, { replace: true })
}, [navigate])
type ScheduleDialogParam = 'scheduleDialog' | 'promptDialog'
type ScheduleEntityParam = 'jobId' | 'templateId'
const replaceUrlParams = useCallback(
(updater: (params: URLSearchParams) => void) => updateParams(updater, 'replace'),
[updateParams],
)
const openEntityDialog = useCallback((
dialogParam: ScheduleDialogParam,
dialogValue: Exclude<ScheduleDialog, null> | Exclude<PromptDialog, null>,
entityParam: ScheduleEntityParam,
entityId: number | null,
) => {
const otherEntityParam = entityParam === 'jobId' ? 'templateId' : 'jobId'
updateParams((p) => {
p.set(dialogParam, dialogValue)
p.delete(entityParam)
p.delete(otherEntityParam)
if (entityId !== null) {
p.set(entityParam, String(entityId))
}
}, 'push')
}, [updateParams])
const setScheduleTab = useCallback((tab: ScheduleTab) => {
replaceUrlParams((p) => {
@@ -90,60 +101,32 @@ export function useScheduleUrlState(): UseScheduleUrlStateReturn {
}, [replaceUrlParams])
const openNewJob = useCallback(() => {
replaceUrlParams((p) => {
p.set('scheduleDialog', 'new')
p.delete('jobId')
p.delete('templateId')
})
}, [replaceUrlParams])
openEntityDialog('scheduleDialog', 'new', 'jobId', null)
}, [openEntityDialog])
const openEditJob = useCallback((id: number) => {
replaceUrlParams((p) => {
p.set('scheduleDialog', 'edit')
p.set('jobId', String(id))
p.delete('templateId')
})
}, [replaceUrlParams])
openEntityDialog('scheduleDialog', 'edit', 'jobId', id)
}, [openEntityDialog])
const openDeleteJob = useCallback((id: number) => {
replaceUrlParams((p) => {
p.set('scheduleDialog', 'delete')
p.set('jobId', String(id))
p.delete('templateId')
})
}, [replaceUrlParams])
openEntityDialog('scheduleDialog', 'delete', 'jobId', id)
}, [openEntityDialog])
const openNewTemplate = useCallback(() => {
replaceUrlParams((p) => {
p.set('promptDialog', 'new')
p.delete('templateId')
p.delete('jobId')
})
}, [replaceUrlParams])
openEntityDialog('promptDialog', 'new', 'templateId', null)
}, [openEntityDialog])
const openEditTemplate = useCallback((id: number) => {
replaceUrlParams((p) => {
p.set('promptDialog', 'edit')
p.set('templateId', String(id))
p.delete('jobId')
})
}, [replaceUrlParams])
openEntityDialog('promptDialog', 'edit', 'templateId', id)
}, [openEntityDialog])
const openDeleteTemplate = useCallback((id: number) => {
replaceUrlParams((p) => {
p.set('promptDialog', 'delete')
p.set('templateId', String(id))
p.delete('jobId')
})
}, [replaceUrlParams])
openEntityDialog('promptDialog', 'delete', 'templateId', id)
}, [openEntityDialog])
const openImportTemplate = useCallback(() => {
replaceUrlParams((p) => {
p.set('promptDialog', 'import')
p.delete('templateId')
p.delete('jobId')
})
}, [replaceUrlParams])
openEntityDialog('promptDialog', 'import', 'templateId', null)
}, [openEntityDialog])
const closeDialog = useCallback(() => {
replaceUrlParams((p) => {
+7 -5
View File
@@ -42,7 +42,7 @@ export function useServerHealth(enabled = true) {
},
onSuccess: () => {
invalidateConfigCaches(queryClient)
toast.success('Server configuration reloaded successfully')
toast.success('Server configuration reloaded successfully', { id: 'reload-config' })
},
onError: (error: unknown) => {
const errorMessage = error && typeof error === 'object' && 'response' in error
@@ -50,7 +50,7 @@ export function useServerHealth(enabled = true) {
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|| 'Failed to reload configuration')
: 'Failed to reload configuration'
toast.error(errorMessage)
toast.error(errorMessage, { id: 'reload-config' })
},
})
@@ -60,10 +60,10 @@ export function useServerHealth(enabled = true) {
},
onSuccess: (data) => {
invalidateSettingsCaches(queryClient)
toast.success(data.message)
toast.success(data.message, { id: 'rollback-config' })
},
onError: () => {
toast.error('Failed to rollback to previous config')
toast.error('Failed to rollback to previous config', { id: 'rollback-config' })
},
})
@@ -91,12 +91,14 @@ export function useServerHealth(enabled = true) {
hasAutoOpenedSettingsRef.current = true
setActiveTab('opencode')
toast.error(health.error || 'OpenCode server requires a password', {
id: 'server-health-password',
duration: Infinity,
description: 'Set a password under Settings → OpenCode to start the server.',
})
} else if (prevHealth && currentStatus !== prevHealth) {
if (isUnhealthy && previousStatus === 'healthy') {
toast.error(health.error || 'OpenCode server is currently unhealthy', {
id: 'server-health-unhealthy',
duration: Infinity,
action: {
label: 'Reload',
@@ -104,7 +106,7 @@ export function useServerHealth(enabled = true) {
},
})
} else if (!isUnhealthy && previousStatus === 'unhealthy') {
toast.success('Server is back online')
toast.success('Server is back online', { id: 'server-health-online' })
hasAutoOpenedSettingsRef.current = false
}
}
@@ -0,0 +1,209 @@
import { useEffect, useRef, useState } from 'react'
import { act, render, screen } from '@testing-library/react'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { describe, it, expect } from 'vitest'
import { useSettingsDialog } from './useSettingsDialog'
import { renderHookWithRouter } from '@/test/test-utils'
describe('useSettingsDialog', () => {
it('returns closed and account tab when no params present', () => {
const { result } = renderHookWithRouter(() => useSettingsDialog())
expect(result.current.isOpen).toBe(false)
expect(result.current.activeTab).toBe('account')
})
it('reads open state and tab from URL', () => {
const { result } = renderHookWithRouter(() => useSettingsDialog(), ['/?settings=open&settingsTab=git'])
expect(result.current.isOpen).toBe(true)
expect(result.current.activeTab).toBe('git')
})
it('defaults activeTab to account when settingsTab is missing', () => {
const { result } = renderHookWithRouter(() => useSettingsDialog(), ['/?settings=open'])
expect(result.current.isOpen).toBe(true)
expect(result.current.activeTab).toBe('account')
})
it('open sets settings=open and settingsTab, clears mobileTab', () => {
const { result } = renderHookWithRouter(() => useSettingsDialog(), ['/?mobileTab=more'])
expect(result.current.isOpen).toBe(false)
act(() => { result.current.open() })
expect(result.current.isOpen).toBe(true)
expect(result.current.activeTab).toBe('account')
})
it('close removes settings and settingsTab params', () => {
const { result } = renderHookWithRouter(() => useSettingsDialog(), ['/?settings=open&settingsTab=git&keep=1'])
expect(result.current.isOpen).toBe(true)
act(() => { result.current.close() })
expect(result.current.isOpen).toBe(false)
expect(result.current.activeTab).toBe('account')
})
it('setActiveTab updates settingsTab param and keeps settings=open', () => {
const { result } = renderHookWithRouter(() => useSettingsDialog(), ['/?settings=open&settingsTab=account'])
act(() => { result.current.setActiveTab('git') })
expect(result.current.isOpen).toBe(true)
expect(result.current.activeTab).toBe('git')
})
it('toggle opens when closed', () => {
const { result } = renderHookWithRouter(() => useSettingsDialog())
expect(result.current.isOpen).toBe(false)
act(() => { result.current.toggle() })
expect(result.current.isOpen).toBe(true)
})
it('toggle closes when open', () => {
const { result } = renderHookWithRouter(() => useSettingsDialog(), ['/?settings=open&settingsTab=general'])
expect(result.current.isOpen).toBe(true)
act(() => { result.current.toggle() })
expect(result.current.isOpen).toBe(false)
})
describe('stable identity', () => {
it('open, close, setActiveTab are stable across rerenders', () => {
const { result, rerender } = renderHookWithRouter(() => useSettingsDialog())
const firstOpen = result.current.open
const firstClose = result.current.close
const firstSetActiveTab = result.current.setActiveTab
rerender()
expect(result.current.open).toBe(firstOpen)
expect(result.current.close).toBe(firstClose)
expect(result.current.setActiveTab).toBe(firstSetActiveTab)
})
it('open, close, setActiveTab are stable across search changes', () => {
const { result, rerender } = renderHookWithRouter(() => useSettingsDialog(), ['/?a=1'])
const firstOpen = result.current.open
const firstClose = result.current.close
const firstSetActiveTab = result.current.setActiveTab
act(() => { result.current.open() })
rerender()
expect(result.current.open).toBe(firstOpen)
expect(result.current.close).toBe(firstClose)
expect(result.current.setActiveTab).toBe(firstSetActiveTab)
})
})
describe('history mode', () => {
it('open pushes so navigate(-1) closes settings', () => {
function Harness() {
const { isOpen, open } = useSettingsDialog()
const navigate = useNavigate()
const [step, setStep] = useState<'start' | 'opened' | 'back'>('start')
const handled = useRef(false)
useEffect(() => {
if (handled.current) return
if (step === 'opened') {
handled.current = true
open()
} else if (step === 'back') {
handled.current = true
navigate(-1)
}
}, [step, open, navigate])
return (
<div>
<span data-testid="dialog-state">{isOpen ? 'open' : 'closed'}</span>
<button onClick={() => { handled.current = false; setStep('opened') }}>
open
</button>
<button onClick={() => { handled.current = false; setStep('back') }}>
back
</button>
</div>
)
}
render(
<MemoryRouter initialEntries={['/']}>
<Harness />
</MemoryRouter>,
)
expect(screen.getByTestId('dialog-state').textContent).toBe('closed')
act(() => { screen.getByText('open').click() })
expect(screen.getByTestId('dialog-state').textContent).toBe('open')
act(() => { screen.getByText('back').click() })
expect(screen.getByTestId('dialog-state').textContent).toBe('closed')
})
it('setActiveTab replaces so navigate(-1) does not step through old tab', () => {
function Harness() {
const { isOpen, activeTab, open, setActiveTab } = useSettingsDialog()
const navigate = useNavigate()
const [step, setStep] = useState<'start' | 'opened' | 'switched' | 'back'>('start')
const handled = useRef(false)
useEffect(() => {
if (handled.current) return
if (step === 'opened') {
handled.current = true
open()
} else if (step === 'switched') {
handled.current = true
setActiveTab('git')
} else if (step === 'back') {
handled.current = true
navigate(-1)
}
}, [step, open, setActiveTab, navigate])
return (
<div>
<span data-testid="dialog-state">{isOpen ? 'open' : 'closed'}</span>
<span data-testid="active-tab">{activeTab}</span>
<button onClick={() => { handled.current = false; setStep('opened') }}>
open
</button>
<button onClick={() => { handled.current = false; setStep('switched') }}>
switch
</button>
<button onClick={() => { handled.current = false; setStep('back') }}>
back
</button>
</div>
)
}
render(
<MemoryRouter initialEntries={['/']}>
<Harness />
</MemoryRouter>,
)
act(() => { screen.getByText('open').click() })
expect(screen.getByTestId('dialog-state').textContent).toBe('open')
expect(screen.getByTestId('active-tab').textContent).toBe('account')
act(() => { screen.getByText('switch').click() })
expect(screen.getByTestId('active-tab').textContent).toBe('git')
act(() => { screen.getByText('back').click() })
// navigate(-1) goes directly to / (pre-settings page), not through old tab
expect(screen.getByTestId('dialog-state').textContent).toBe('closed')
expect(screen.getByTestId('active-tab').textContent).toBe('account')
})
})
})
+26 -23
View File
@@ -1,5 +1,5 @@
import { useCallback } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useCallback, useRef } from 'react'
import { useUrlParams } from './useUrlParams'
type Tab = 'account' | 'general' | 'notifications' | 'voice' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'menu'
@@ -13,41 +13,44 @@ interface UseSettingsDialogReturn {
}
export function useSettingsDialog(): UseSettingsDialogReturn {
const navigate = useNavigate()
const location = useLocation()
const { searchParams, updateParams } = useUrlParams()
const searchParams = new URLSearchParams(location.search)
const isOpen = searchParams.get('settings') === 'open'
const activeTab = (searchParams.get('tab') as Tab) || 'account'
const activeTab = (searchParams.get('settingsTab') as Tab) || 'account'
const activeTabRef = useRef(activeTab)
activeTabRef.current = activeTab
const open = useCallback(() => {
const newParams = new URLSearchParams(location.search)
newParams.set('settings', 'open')
newParams.set('tab', activeTab)
navigate({ search: newParams.toString() }, { replace: true })
}, [activeTab, navigate, location.search])
updateParams((p) => {
p.set('settings', 'open')
p.set('settingsTab', activeTabRef.current)
p.delete('mobileTab')
}, 'push')
}, [updateParams])
const close = useCallback(() => {
const newParams = new URLSearchParams(location.search)
newParams.delete('settings')
newParams.delete('tab')
navigate({ search: newParams.toString() }, { replace: true })
}, [navigate, location.search])
updateParams((p) => {
p.delete('settings')
p.delete('settingsTab')
}, 'replace')
}, [updateParams])
const toggle = useCallback(() => {
if (isOpen) {
const isCurrentlyOpen = searchParams.get('settings') === 'open'
if (isCurrentlyOpen) {
close()
} else {
open()
}
}, [isOpen, open, close])
}, [searchParams, open, close])
const setActiveTab = useCallback((tab: Tab) => {
const newParams = new URLSearchParams(location.search)
newParams.set('settings', 'open')
newParams.set('tab', tab)
navigate({ search: newParams.toString() }, { replace: true })
}, [navigate, location.search])
updateParams((p) => {
p.set('settings', 'open')
p.set('settingsTab', tab)
}, 'replace')
}, [updateParams])
return {
isOpen,
+203
View File
@@ -0,0 +1,203 @@
import { useEffect, useRef, useState } from 'react'
import { act, render, screen } from '@testing-library/react'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { describe, it, expect } from 'vitest'
import { useUrlParams } from './useUrlParams'
import { renderHookWithRouterAndLocation } from '@/test/test-utils'
describe('useUrlParams', () => {
it('exports the expected API surface', () => {
expect(typeof useUrlParams).toBe('function')
const { result } = renderHookWithRouterAndLocation(() => useUrlParams())
expect(typeof result.current.search).toBe('string')
expect(typeof result.current.searchParams).toBe('object')
expect(result.current.searchParams instanceof URLSearchParams).toBe(true)
expect(typeof result.current.updateParams).toBe('function')
})
it('returns initial search string and searchParams from location', () => {
const { result } = renderHookWithRouterAndLocation(() => useUrlParams(), ['/?foo=1&bar=2'])
expect(result.current.search).toBe('?foo=1&bar=2')
expect(result.current.searchParams.get('foo')).toBe('1')
expect(result.current.searchParams.get('bar')).toBe('2')
})
it('returns empty search when no params', () => {
const { result } = renderHookWithRouterAndLocation(() => useUrlParams(), ['/'])
expect(result.current.search).toBe('')
})
describe('updateParams', () => {
it('sets a param and preserves unrelated params', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useUrlParams(), ['/?keep=1'])
act(() => {
result.current.updateParams((p) => p.set('dialog', 'mcp'))
})
expect(result.current.search).toContain('dialog=mcp')
expect(result.current.search).toContain('keep=1')
expect(capturedSearch.current).toContain('dialog=mcp')
expect(capturedSearch.current).toContain('keep=1')
})
it('deletes a param without affecting others', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useUrlParams(), ['/?foo=1&bar=2'])
act(() => {
result.current.updateParams((p) => p.delete('foo'))
})
expect(result.current.search).not.toContain('foo')
expect(result.current.search).toContain('bar=2')
expect(capturedSearch.current).not.toContain('foo')
expect(capturedSearch.current).toContain('bar=2')
})
it('sets and deletes multiple params atomically', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useUrlParams(), ['/?a=1&b=2&c=3'])
act(() => {
result.current.updateParams((p) => {
p.set('x', '10')
p.delete('a')
p.set('b', 'updated')
})
})
expect(result.current.search).toContain('x=10')
expect(result.current.search).toContain('b=updated')
expect(result.current.search).toContain('c=3')
expect(result.current.search).not.toContain('a=')
expect(capturedSearch.current).toContain('x=10')
expect(capturedSearch.current).toContain('b=updated')
expect(capturedSearch.current).toContain('c=3')
expect(capturedSearch.current).not.toContain('a=')
})
it('preserves all params when updater makes no changes', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useUrlParams(), ['/?foo=1&bar=2'])
act(() => {
result.current.updateParams((_p) => {})
})
expect(result.current.search).toContain('foo=1')
expect(result.current.search).toContain('bar=2')
expect(capturedSearch.current).toContain('foo=1')
expect(capturedSearch.current).toContain('bar=2')
})
it('handles special characters in param values', () => {
const { result } = renderHookWithRouterAndLocation(() => useUrlParams())
act(() => {
result.current.updateParams((p) => p.set('q', 'hello world & more'))
})
expect(result.current.search).toContain('q=hello+world+%26+more')
})
})
describe('mode: replace (default)', () => {
it('defaults to replace mode when no mode arg passed', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(() => useUrlParams(), ['/?initial=1'])
act(() => {
result.current.updateParams((p) => p.set('added', 'yes'))
})
expect(capturedSearch.current).toContain('initial=1')
expect(capturedSearch.current).toContain('added=yes')
})
it('explicit replace does not push a new history entry', () => {
const { result } = renderHookWithRouterAndLocation(() => useUrlParams(), ['/?x=1'])
act(() => {
result.current.updateParams((p) => p.set('x', '2'), 'replace')
})
expect(result.current.search).toContain('x=2')
})
})
describe('mode: push', () => {
it('push adds a new history entry that navigate(-1) reverses', () => {
function PushHarness() {
const { search, updateParams } = useUrlParams()
const navigate = useNavigate()
const [step, setStep] = useState<'start' | 'pushed' | 'back'>('start')
const handled = useRef(false)
useEffect(() => {
if (handled.current) return
if (step === 'pushed') {
handled.current = true
updateParams((p) => p.set('dialog', 'open'), 'push')
} else if (step === 'back') {
handled.current = true
navigate(-1)
}
}, [step, updateParams, navigate])
return (
<div>
<span data-testid="search">{search}</span>
<button onClick={() => { handled.current = false; setStep('pushed') }}>
push
</button>
<button onClick={() => { handled.current = false; setStep('back') }}>
back
</button>
</div>
)
}
render(
<MemoryRouter initialEntries={['/']}>
<PushHarness />
</MemoryRouter>,
)
expect(screen.getByTestId('search').textContent).toBe('')
act(() => {
screen.getByText('push').click()
})
expect(screen.getByTestId('search').textContent).toContain('dialog=open')
act(() => {
screen.getByText('back').click()
})
expect(screen.getByTestId('search').textContent).not.toContain('dialog=open')
})
})
describe('stable identity', () => {
it('updateParams reference is stable across location.search changes', () => {
const { result, rerender } = renderHookWithRouterAndLocation(() => useUrlParams(), ['/?a=1'])
const firstUpdateParams = result.current.updateParams
act(() => {
result.current.updateParams((p) => p.set('b', '2'))
})
rerender()
expect(result.current.updateParams).toBe(firstUpdateParams)
})
it('updateParams reference is stable across multiple updates', () => {
const { result } = renderHookWithRouterAndLocation(() => useUrlParams())
const firstUpdateParams = result.current.updateParams
act(() => {
result.current.updateParams((p) => p.set('a', '1'))
})
act(() => {
result.current.updateParams((p) => p.set('b', '2'))
})
expect(result.current.updateParams).toBe(firstUpdateParams)
})
it('updateParams reference remains stable when no navigation occurs', () => {
const { result, rerender } = renderHookWithRouterAndLocation(() => useUrlParams())
const firstUpdateParams = result.current.updateParams
rerender()
expect(result.current.updateParams).toBe(firstUpdateParams)
})
})
})
+33
View File
@@ -0,0 +1,33 @@
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
type UrlHistoryMode = 'push' | 'replace'
interface UseUrlParamsReturn {
search: string
searchParams: URLSearchParams
updateParams: (updater: (params: URLSearchParams) => void, mode?: UrlHistoryMode) => void
}
export function useUrlParams(): UseUrlParamsReturn {
const navigate = useNavigate()
const location = useLocation()
const searchRef = useRef(location.search)
useEffect(() => {
searchRef.current = location.search
}, [location.search])
const searchParams = useMemo(() => new URLSearchParams(location.search), [location.search])
const updateParams = useCallback(
(updater: (params: URLSearchParams) => void, mode: UrlHistoryMode = 'replace') => {
const params = new URLSearchParams(searchRef.current)
updater(params)
navigate({ search: params.toString() }, { replace: mode === 'replace' })
},
[navigate],
)
return { search: location.search, searchParams, updateParams }
}
@@ -0,0 +1,99 @@
import { useEffect, useRef, useState } from 'react'
import { act, render, screen } from '@testing-library/react'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { describe, it, expect } from 'vitest'
import { useWorktreeTab } from './useWorktreeTab'
import { renderHookWithRouter } from '@/test/test-utils'
describe('useWorktreeTab', () => {
it('defaults activeTab to repo when no repoTab param', () => {
const { result } = renderHookWithRouter(() => useWorktreeTab())
expect(result.current.activeTab).toBe('repo')
})
it('reads workspaces from repoTab param', () => {
const { result } = renderHookWithRouter(() => useWorktreeTab(), ['/?repoTab=workspaces'])
expect(result.current.activeTab).toBe('workspaces')
})
it('defaults to repo for unrecognized repoTab values', () => {
const { result } = renderHookWithRouter(() => useWorktreeTab(), ['/?repoTab=invalid'])
expect(result.current.activeTab).toBe('repo')
})
it('setActiveTab(workspaces) sets repoTab=workspaces', () => {
const { result } = renderHookWithRouter(() => useWorktreeTab())
act(() => { result.current.setActiveTab('workspaces') })
expect(result.current.activeTab).toBe('workspaces')
})
it('setActiveTab(repo) removes repoTab param', () => {
const { result } = renderHookWithRouter(() => useWorktreeTab(), ['/?repoTab=workspaces'])
expect(result.current.activeTab).toBe('workspaces')
act(() => { result.current.setActiveTab('repo') })
expect(result.current.activeTab).toBe('repo')
})
it('setActiveTab uses replace so navigate(-1) does not step through tab changes', () => {
function Harness() {
const { activeTab, setActiveTab } = useWorktreeTab()
const navigate = useNavigate()
const [step, setStep] = useState<'start' | 'switched' | 'back'>('start')
const handled = useRef(false)
useEffect(() => {
if (handled.current) return
if (step === 'switched') {
handled.current = true
setActiveTab('workspaces')
} else if (step === 'back') {
handled.current = true
navigate(-1)
}
}, [step, setActiveTab, navigate])
return (
<div>
<span data-testid="activeTab">{activeTab}</span>
<button onClick={() => { handled.current = false; setStep('switched') }}>
switch
</button>
<button onClick={() => { handled.current = false; setStep('back') }}>
back
</button>
</div>
)
}
render(
<MemoryRouter initialEntries={['/other', '/']}>
<Harness />
</MemoryRouter>,
)
expect(screen.getByTestId('activeTab').textContent).toBe('repo')
act(() => { screen.getByText('switch').click() })
expect(screen.getByTestId('activeTab').textContent).toBe('workspaces')
act(() => { screen.getByText('back').click() })
expect(screen.getByTestId('activeTab').textContent).toBe('repo')
})
describe('stable identity', () => {
it('setActiveTab is stable across rerenders', () => {
const { result, rerender } = renderHookWithRouter(() => useWorktreeTab())
const firstSetActiveTab = result.current.setActiveTab
rerender()
expect(result.current.setActiveTab).toBe(firstSetActiveTab)
})
it('setActiveTab is stable across search changes', () => {
const { result, rerender } = renderHookWithRouter(() => useWorktreeTab(), ['/?a=1'])
const firstSetActiveTab = result.current.setActiveTab
act(() => { result.current.setActiveTab('workspaces') })
rerender()
expect(result.current.setActiveTab).toBe(firstSetActiveTab)
})
})
})
+13 -23
View File
@@ -1,37 +1,27 @@
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useCallback } from 'react'
import { useUrlParams } from './useUrlParams'
export type WorktreeTabValue = 'repo' | 'workspaces'
export interface UseWorktreeTabReturn {
interface UseWorktreeTabReturn {
activeTab: WorktreeTabValue
setActiveTab: (tab: WorktreeTabValue) => void
}
export function useWorktreeTab(): UseWorktreeTabReturn {
const navigate = useNavigate()
const location = useLocation()
const searchRef = useRef(location.search)
const { searchParams, updateParams } = useUrlParams()
useEffect(() => {
searchRef.current = location.search
}, [location.search])
const activeTab = useMemo<WorktreeTabValue>(() => {
const searchParams = new URLSearchParams(location.search)
const tabParam = searchParams.get('tab')
return tabParam === 'workspaces' ? 'workspaces' : 'repo'
}, [location.search])
const activeTab: WorktreeTabValue = searchParams.get('repoTab') === 'workspaces' ? 'workspaces' : 'repo'
const setActiveTab = useCallback((tab: WorktreeTabValue) => {
const newParams = new URLSearchParams(searchRef.current)
if (tab === 'repo') {
newParams.delete('tab')
} else {
newParams.set('tab', tab)
}
navigate({ search: newParams.toString() }, { replace: true })
}, [navigate])
updateParams((p) => {
if (tab === 'repo') {
p.delete('repoTab')
} else {
p.set('repoTab', tab)
}
}, 'replace')
}, [updateParams])
return {
activeTab,
+25 -4
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath } from './navigation';
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath } from './navigation';
describe('getAssistantPath', () => {
it('returns /assistant', () => {
@@ -47,7 +47,7 @@ describe('getSessionListPath', () => {
});
it('includes tab param when tab is workspaces', () => {
expect(getSessionListPath(42, false, 'workspaces')).toBe('/repos/42?tab=workspaces');
expect(getSessionListPath(42, false, 'workspaces')).toBe('/repos/42?repoTab=workspaces');
});
it('omits tab param for repo/default tab', () => {
@@ -60,6 +60,21 @@ describe('getSessionListPath', () => {
});
});
describe('return target helpers', () => {
it('adds encoded returnTo params for internal paths', () => {
expect(getPathWithReturnTo('/repos/5/schedules', '/repos/5/sessions/abc?assistant=1')).toBe(
'/repos/5/schedules?returnTo=%2Frepos%2F5%2Fsessions%2Fabc%3Fassistant%3D1'
);
});
it('reads returnTo params and falls back for unsafe values', () => {
expect(getReturnToPath('?returnTo=%2Frepos%2F5%2Fsessions%2Fabc%3Fassistant%3D1', '/repos/5')).toBe(
'/repos/5/sessions/abc?assistant=1'
);
expect(getReturnToPath('?returnTo=https%3A%2F%2Fexample.com', '/repos/5')).toBe('/repos/5');
});
});
describe('getSwipeBackTarget', () => {
describe('session detail routes', () => {
it('returns repo path for normal session detail', () => {
@@ -82,8 +97,8 @@ describe('getSwipeBackTarget', () => {
});
it('preserves tab param in back target', () => {
expect(getSwipeBackTarget('/repos/42/sessions/abc', '?tab=workspaces')).toBe('/repos/42?tab=workspaces');
expect(getSwipeBackTarget('/repos/42/sessions/abc', '?tab=workspaces&assistant=1')).toBe(
expect(getSwipeBackTarget('/repos/42/sessions/abc', '?repoTab=workspaces')).toBe('/repos/42?repoTab=workspaces');
expect(getSwipeBackTarget('/repos/42/sessions/abc', '?repoTab=workspaces&assistant=1')).toBe(
'/assistant?view=sessions'
);
});
@@ -123,6 +138,12 @@ describe('getSwipeBackTarget', () => {
expect(getSwipeBackTarget('/repos/42/schedules', '')).toBe('/repos/42');
});
it('returns returnTo path for repo schedules when present', () => {
expect(getSwipeBackTarget('/repos/42/schedules', '?returnTo=%2Frepos%2F42%2Fsessions%2Fabc%3Fassistant%3D1')).toBe(
'/repos/42/sessions/abc?assistant=1'
);
});
it('returns root for top-level schedules', () => {
expect(getSwipeBackTarget('/schedules', '')).toBe('/');
});
+22 -2
View File
@@ -16,11 +16,29 @@ export function getSessionListPath(repoId: string | number, isAssistantSession:
}
const base = `/repos/${String(repoId)}`;
if (tab && tab !== 'repo') {
return `${base}?tab=${tab}`;
return `${base}?repoTab=${tab}`;
}
return base;
}
function isSafeInternalPath(path: string): boolean {
return path.startsWith('/') && !path.startsWith('//');
}
export function getPathWithReturnTo(path: string, returnTo: string): string {
if (!isSafeInternalPath(returnTo)) return path;
const [base, query = ''] = path.split('?');
const params = new URLSearchParams(query);
params.set('returnTo', returnTo);
const search = params.toString();
return search ? `${base}?${search}` : base;
}
export function getReturnToPath(search: string, fallback: string): string {
const returnTo = new URLSearchParams(search).get('returnTo');
return returnTo && isSafeInternalPath(returnTo) ? returnTo : fallback;
}
export function getSwipeBackTarget(pathname: string, search = ''): string | null {
const sessionDetailRegex = /^\/repos\/([^/]+)\/sessions\/[^/]+$/;
const match = pathname.match(sessionDetailRegex);
@@ -29,7 +47,7 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null
const repoId = match[1];
const params = new URLSearchParams(search);
const isAssistant = params.get('assistant') === '1';
const tab = params.get('tab') ?? undefined;
const tab = params.get('repoTab') ?? undefined;
return getSessionListPath(repoId, isAssistant, tab);
}
@@ -46,6 +64,8 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null
}
if (/^\/repos\/[^/]+\/schedules$/.test(pathname)) {
const returnTo = getReturnToPath(search, '');
if (returnTo) return returnTo;
const repoId = pathname.split('/')[2];
if (repoId === '0') {
return getAssistantPath();
+3 -22
View File
@@ -4,12 +4,12 @@ import { useAllSchedules, useAllScheduleRuns, useCancelRepoScheduleRun } from '@
import { useDeleteRepoSchedule, useRunRepoSchedule, useUpdateRepoSchedule, useCreateRepoSchedule } from '@/hooks/useSchedules'
import { ScheduleJobDialog, RunHistoryCards, PromptsTab } from '@/components/schedules'
import type { CreateScheduleJobRequest } from '@opencode-manager/shared/types'
import { toUpdateScheduleRequest, formatScheduleShortLabel, getJobStatusTone, formatTimestamp } from '@/components/schedules/schedule-utils'
import { toUpdateScheduleRequest, formatScheduleShortLabel, formatTimestamp, getJobStatusTone } from '@/components/schedules/schedule-utils'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuCheckboxItem, DropdownMenuItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { CalendarClock, Loader2, Plus, ArrowLeft, Play, Pencil, Trash2, Pause, PlayCircle, Clock3, History, SlidersHorizontal } from 'lucide-react'
@@ -159,17 +159,6 @@ export function GlobalSchedules() {
return filtered
}, [jobs, statusFilter, scheduleModeFilter, repoFilter, sortOption])
const stats = useMemo(() => {
const total = jobs.length
const enabled = jobs.filter((j) => j.enabled).length
const disabled = total - enabled
const now = Date.now()
const last24h = now - 24 * 60 * 60 * 1000
const recentRuns = jobs.filter((j) => j.lastRunAt && j.lastRunAt > last24h)
return { total, enabled, disabled, recentRuns: recentRuns.length }
}, [jobs])
const repoOptions = useMemo(() => [
{ value: 'all', label: 'All Repos', description: `${jobs.length} total jobs` },
...uniqueRepos.map((repo) => ({
@@ -324,12 +313,6 @@ export function GlobalSchedules() {
<Header.BackButton to="/" />
<Header.Title>Schedules</Header.Title>
<div className="flex items-center gap-2">
<Badge variant="outline" className="hidden sm:inline-flex h-6 rounded-full px-2 text-xs">
{stats.total} total
</Badge>
<Badge variant="outline" className="h-6 rounded-full px-2 text-xs bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20">
{stats.enabled} enabled
</Badge>
<Header.Actions>
<Button
onClick={() => { openNewJob(); setSelectedRepoId(undefined) }}
@@ -588,9 +571,7 @@ export function GlobalSchedules() {
{job.description || 'No description'}
</p>
</div>
<Badge className={getJobStatusTone(job)}>
{job.enabled ? 'Enabled' : 'Paused'}
</Badge>
<Badge className={getJobStatusTone(job)}>{job.enabled ? 'Enabled' : 'Paused'}</Badge>
</div>
<div className="space-y-2 text-xs text-muted-foreground">
+1 -1
View File
@@ -108,7 +108,7 @@ export function RepoDetail() {
const sessionUrl = useCallback(
(sessionId: string) => {
const base = `/repos/${repoId}/sessions/${sessionId}`;
return activeTab === 'workspaces' ? `${base}?tab=workspaces` : base;
return activeTab === 'workspaces' ? `${base}?repoTab=workspaces` : base;
},
[repoId, activeTab],
);
+6 -8
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo } from 'react'
import { useParams } from 'react-router-dom'
import { useLocation, useParams } from 'react-router-dom'
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
import {
useCancelRepoScheduleRun,
@@ -16,17 +16,17 @@ import { useRepoActivity } from '@/hooks/useRepoActivity'
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
import { useScheduleUrlState } from '@/hooks/useScheduleUrlState'
import { ScheduleJobDialog, JobsTab, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
import { toUpdateScheduleRequest, getJobStatusTone } from '@/components/schedules/schedule-utils'
import { toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { cn } from '@/lib/utils'
import { getReturnToPath } from '@/lib/navigation'
import { CalendarClock, Loader2, Plus } from 'lucide-react'
export function Schedules() {
const { id } = useParams<{ id: string }>()
const location = useLocation()
const repoId = id ? Number(id) : undefined
const {
@@ -135,8 +135,8 @@ export function Schedules() {
</div>
)
}
const enabledCount = jobs?.filter((job) => job.enabled).length ?? 0
const hasJobs = (jobs?.length ?? 0) > 0
const backHref = getReturnToPath(location.search, scheduleTarget.backHref)
const handleCreate = (data: CreateScheduleJobRequest) => {
createMutation.mutate({ repoId: repoId!, data }, {
@@ -222,14 +222,12 @@ export function Schedules() {
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
<Header>
<Header.BackButton to={scheduleTarget.backHref} />
<Header.BackButton to={backHref} />
<div className="min-w-0 flex-1 px-3">
<Header.Title className="truncate">{scheduleTarget.name}</Header.Title>
<p className="text-xs text-muted-foreground truncate">{scheduleTarget.subtitle}</p>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="h-6 rounded-full px-2 text-xs">{jobs?.length ?? 0} jobs</Badge>
<Badge variant="outline" className={cn('h-6 rounded-full px-2 text-xs', getJobStatusTone({ enabled: true } as ScheduleJob))}>{enabledCount} enabled</Badge>
<Header.Actions>
<Button onClick={openNewJob} size="sm" className="hidden sm:flex">
<Plus className="w-4 h-4 mr-2" />
+2 -2
View File
@@ -303,7 +303,7 @@ export function SessionDetail() {
}, [opcodeUrl, sessionId, repoDirectory, navigate, repoId, sessionRouteSuffix]);
const handleCloseSession = useCallback(() => {
const tab = new URLSearchParams(location.search).get('tab') ?? undefined;
const tab = new URLSearchParams(location.search).get('repoTab') ?? undefined;
navigate(getSessionListPath(repoId, isAssistantSession, tab))
}, [navigate, repoId, isAssistantSession, location.search])
@@ -428,7 +428,7 @@ export function SessionDetail() {
const workspaceDisplayName = isAssistantSession || !repo
? 'Assistant'
: getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
const tabFromUrl = new URLSearchParams(location.search).get('tab') ?? undefined;
const tabFromUrl = new URLSearchParams(location.search).get('repoTab') ?? undefined;
const sessionBackPath = getSessionListPath(repoId, isAssistantSession, tabFromUrl);
return (
@@ -109,9 +109,9 @@ const createWrapper = () => {
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
const renderSchedules = (repoId: string) => {
const renderSchedules = (repoId: string, initialEntry = `/repos/${repoId}/schedules`) => {
return render(
<MemoryRouter initialEntries={[`/repos/${repoId}/schedules`]}>
<MemoryRouter initialEntries={[initialEntry]}>
<Routes>
<Route path="/repos/:id/schedules" element={<Schedules />} />
</Routes>
@@ -310,6 +310,33 @@ describe('Schedules', () => {
expect(mockNavigate).toHaveBeenCalledWith('/repos/5')
})
it('uses returnTo param for back button when present', () => {
mockNavigate.mockClear()
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
subtitle: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
backHref: '/repos/5',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('5', '/repos/5/schedules?returnTo=%2Frepos%2F5%2Fsessions%2Fabc%3Fassistant%3D1')
fireEvent.click(screen.getAllByRole('button')[0])
expect(mockNavigate).toHaveBeenCalledWith('/repos/5/sessions/abc?assistant=1')
})
it('normalizes prompts tab to jobs when jobs exist', () => {
const setScheduleTab = vi.fn()
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({
-4
View File
@@ -8,14 +8,12 @@ interface UIStateStore {
activePromptFileBasePath: string | null
pendingPromptCommand: { id: number; command: CommandType } | null
pendingPromptFile: { id: number; path: string } | null
isMoreDrawerOpen: boolean
setIsEditingMessage: (isEditing: boolean) => void
setActivePromptFileBasePath: (basePath: string | null) => void
selectPromptCommand: (command: CommandType) => void
clearPendingPromptCommand: () => void
selectPromptFile: (path: string) => void
clearPendingPromptFile: () => void
setMoreDrawerOpen: (open: boolean) => void
}
export const useUIState = create<UIStateStore>((set) => ({
@@ -23,12 +21,10 @@ export const useUIState = create<UIStateStore>((set) => ({
activePromptFileBasePath: null,
pendingPromptCommand: null,
pendingPromptFile: null,
isMoreDrawerOpen: false,
setIsEditingMessage: (isEditing: boolean) => set({ isEditingMessage: isEditing }),
setActivePromptFileBasePath: (basePath: string | null) => set({ activePromptFileBasePath: basePath }),
selectPromptCommand: (command: CommandType) => set({ pendingPromptCommand: { id: Date.now(), command } }),
clearPendingPromptCommand: () => set({ pendingPromptCommand: null }),
selectPromptFile: (path: string) => set({ pendingPromptFile: { id: Date.now(), path } }),
clearPendingPromptFile: () => set({ pendingPromptFile: null }),
setMoreDrawerOpen: (open: boolean) => set({ isMoreDrawerOpen: open }),
}))
+37
View File
@@ -0,0 +1,37 @@
/* eslint-disable react-refresh/only-export-components */
import { useEffect, type ReactNode } from 'react'
import { renderHook } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router-dom'
export function createRouterWrapper(initialEntries?: string[]) {
return function Wrapper({ children }: { children: ReactNode }) {
return <MemoryRouter initialEntries={initialEntries}>{children}</MemoryRouter>
}
}
export function renderHookWithRouter<T>(renderFn: () => T, initialEntries?: string[]) {
return renderHook(renderFn, { wrapper: createRouterWrapper(initialEntries) })
}
export function LocationCatcher({ capturedSearch }: { capturedSearch: { current: string } }) {
const location = useLocation()
useEffect(() => {
capturedSearch.current = location.search
})
return null
}
export function renderHookWithRouterAndLocation<T>(renderFn: () => T, initialEntries?: string[]) {
const capturedSearch: { current: string } = { current: '' }
const wrapper = function Wrapper({ children }: { children: ReactNode }) {
return (
<MemoryRouter initialEntries={initialEntries}>
<LocationCatcher capturedSearch={capturedSearch} />
{children}
</MemoryRouter>
)
}
const rendered = renderHook(renderFn, { wrapper })
return { ...rendered, capturedSearch }
}