mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(schedules): add unread run report notifications and run search
This commit is contained in:
1 parent
7cac8baade
commit
5a8a81419c
43 files changed
+2463
-798
No files matched your search
@@ -4,13 +4,24 @@ import type {
|
||||
CreateScheduleJobRequest,
|
||||
ScheduleJob,
|
||||
ScheduleRun,
|
||||
ScheduleRunStatus,
|
||||
UpdateScheduleJobRequest,
|
||||
} from '@opencode-manager/shared/types'
|
||||
|
||||
export interface ScheduleRunSummary {
|
||||
id: number
|
||||
status: ScheduleRunStatus
|
||||
startedAt: number
|
||||
finishedAt: number | null
|
||||
viewedAt: number | null
|
||||
preview: string | null
|
||||
}
|
||||
|
||||
export interface ScheduleJobWithRepo extends ScheduleJob {
|
||||
repoName: string
|
||||
repoPath: string
|
||||
repoUrl: string
|
||||
lastRun: ScheduleRunSummary | null
|
||||
}
|
||||
|
||||
export interface ScheduleRunWithContext extends ScheduleRun {
|
||||
@@ -19,6 +30,16 @@ export interface ScheduleRunWithContext extends ScheduleRun {
|
||||
repoPath: string
|
||||
}
|
||||
|
||||
export interface UnreadScheduleRun extends ScheduleRunWithContext {
|
||||
preview: string | null
|
||||
}
|
||||
|
||||
export interface UnreadScheduleRunsResponse {
|
||||
runs: UnreadScheduleRun[]
|
||||
total: number
|
||||
failed: number
|
||||
}
|
||||
|
||||
export interface ListAllRunsParams {
|
||||
limit?: number
|
||||
offset?: number
|
||||
@@ -27,6 +48,7 @@ export interface ListAllRunsParams {
|
||||
jobId?: number
|
||||
triggerSource?: string
|
||||
runId?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export interface ScheduleCount {
|
||||
@@ -47,12 +69,25 @@ export async function listAllScheduleRuns(params: ListAllRunsParams = {}): Promi
|
||||
if (params.jobId !== undefined) searchParams.set('jobId', String(params.jobId))
|
||||
if (params.triggerSource) searchParams.set('triggerSource', params.triggerSource)
|
||||
if (params.runId !== undefined) searchParams.set('runId', String(params.runId))
|
||||
if (params.search) searchParams.set('search', params.search)
|
||||
const qs = searchParams.toString()
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function listRepoSchedules(repoId: number): Promise<{ jobs: ScheduleJob[] }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules`)
|
||||
export async function listUnreadScheduleRuns(limit: number = 20): Promise<UnreadScheduleRunsResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs/unread?limit=${limit}`)
|
||||
}
|
||||
|
||||
export async function markScheduleRunViewed(runId: number): Promise<{ updated: boolean }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs/${runId}/viewed`, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function markAllScheduleRunsViewed(): Promise<{ updated: number }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs/viewed`, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function getScheduleCounts(): Promise<Map<number, ScheduleCount>> {
|
||||
|
||||
@@ -4,6 +4,10 @@ vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useUnreadScheduleRuns: vi.fn(() => ({ data: undefined })),
|
||||
}))
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useMobile } from '@/hooks/useMobile'
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { useScheduleUrlState, type ScheduleTab } from '@/hooks/useScheduleUrlState'
|
||||
import { useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { getAssistantPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation'
|
||||
import { openDialogParam } from '@/hooks/useDialogParam'
|
||||
|
||||
@@ -27,6 +28,7 @@ interface GlobalTabsArgs {
|
||||
isInsideRepo: boolean
|
||||
repoId: number | null
|
||||
updateParams: ReturnType<typeof useUrlParams>['updateParams']
|
||||
unreadScheduleCount: number
|
||||
}
|
||||
|
||||
type TabBarMode = 'hidden' | 'global' | 'schedule'
|
||||
@@ -62,7 +64,7 @@ function getMobileTabRouteState(pathname: string): MobileTabRouteState {
|
||||
}
|
||||
}
|
||||
|
||||
function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideRepo, repoId, updateParams }: GlobalTabsArgs): TabDef[] {
|
||||
function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideRepo, repoId, updateParams, unreadScheduleCount }: GlobalTabsArgs): TabDef[] {
|
||||
const openRepoDialog = (dialog: string) => {
|
||||
openDialogParam(updateParams, dialog)
|
||||
}
|
||||
@@ -120,6 +122,7 @@ function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideR
|
||||
icon: CalendarClock,
|
||||
onClick: () => navigate('/schedules'),
|
||||
active: pathname === '/schedules' && !openSheet,
|
||||
badge: unreadScheduleCount > 0,
|
||||
}]
|
||||
: []),
|
||||
{
|
||||
@@ -199,8 +202,10 @@ export const MobileTabBar = memo(function MobileTabBar() {
|
||||
const { openSheet, open, close } = useMobileTabBar()
|
||||
const { updateParams } = useUrlParams()
|
||||
const { scheduleTab, setScheduleTab } = useScheduleUrlState()
|
||||
const { data: unreadRuns } = useUnreadScheduleRuns()
|
||||
const isMobile = useMobile()
|
||||
const routeState = useMemo(() => getMobileTabRouteState(pathname), [pathname])
|
||||
const unreadScheduleCount = unreadRuns?.total ?? 0
|
||||
|
||||
const tabs = useMemo<TabDef[]>(
|
||||
() => (routeState.mode === 'schedule'
|
||||
@@ -214,6 +219,7 @@ export const MobileTabBar = memo(function MobileTabBar() {
|
||||
isInsideRepo: routeState.isInsideRepo,
|
||||
repoId: routeState.repoId,
|
||||
updateParams,
|
||||
unreadScheduleCount,
|
||||
})),
|
||||
[
|
||||
routeState,
|
||||
@@ -225,6 +231,7 @@ export const MobileTabBar = memo(function MobileTabBar() {
|
||||
close,
|
||||
navigate,
|
||||
updateParams,
|
||||
unreadScheduleCount,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Bell, HelpCircle } from 'lucide-react'
|
||||
import { PendingActionBadge } from '@/components/ui/pending-action-badge'
|
||||
import { ScheduleReportsBell } from '@/components/notifications/ScheduleReportsBell'
|
||||
import { usePermissions, useForms } from '@/contexts/EventContext'
|
||||
|
||||
export function PendingActionsGroup() {
|
||||
@@ -8,6 +9,7 @@ export function PendingActionsGroup() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<ScheduleReportsBell />
|
||||
<PendingActionBadge
|
||||
count={permissionCount}
|
||||
icon={Bell}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { ScheduleReportsBell } from './ScheduleReportsBell'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useUnreadScheduleRuns: vi.fn(),
|
||||
useMarkAllScheduleRunsViewed: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useUnreadScheduleRuns: mocks.useUnreadScheduleRuns,
|
||||
useMarkAllScheduleRunsViewed: mocks.useMarkAllScheduleRunsViewed,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: vi.fn(() => false),
|
||||
}))
|
||||
|
||||
function renderBell() {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<ScheduleReportsBell />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('ScheduleReportsBell', () => {
|
||||
beforeAll(() => {
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
Element.prototype.setPointerCapture ??= () => {}
|
||||
Element.prototype.releasePointerCapture ??= () => {}
|
||||
Element.prototype.scrollIntoView ??= () => {}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useMarkAllScheduleRunsViewed.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
})
|
||||
|
||||
it('renders the unread count badge', () => {
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 3, failed: 0 } })
|
||||
renderBell()
|
||||
|
||||
expect(screen.getByText('3')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses destructive styling when a run failed', () => {
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 3, failed: 1 } })
|
||||
renderBell()
|
||||
|
||||
expect(screen.getByTestId('schedule-reports-count')).toHaveClass('bg-destructive')
|
||||
})
|
||||
|
||||
it('shows the all-caught-up empty state when there are no unread runs', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 0, failed: 0 } })
|
||||
renderBell()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reports, 0 unread' }))
|
||||
|
||||
expect(await screen.findByText('All caught up')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useState } from 'react'
|
||||
import { Link, useNavigate } from 'react-router-dom'
|
||||
import { CheckCircle2, Inbox, XCircle } from 'lucide-react'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
|
||||
import { BottomSheet, BottomSheetContent, BottomSheetHeader } from '@/components/ui/bottom-sheet'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useMarkAllScheduleRunsViewed, useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { UnreadScheduleRun } from '@/api/schedules'
|
||||
|
||||
function ScheduleReportsCount({ total, failed }: { total: number; failed: number }) {
|
||||
if (total <= 0) return null
|
||||
|
||||
return (
|
||||
<span
|
||||
data-testid="schedule-reports-count"
|
||||
className={cn(
|
||||
'absolute -top-1 -right-1 min-w-4 rounded-full px-1 text-center text-[10px] font-medium leading-4 text-primary-foreground',
|
||||
failed > 0 ? 'bg-destructive' : 'bg-primary',
|
||||
)}
|
||||
>
|
||||
{total > 9 ? '9+' : total}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function ScheduleReportRow({ run, rowClassName, onClick }: { run: UnreadScheduleRun; rowClassName?: string; onClick: () => void }) {
|
||||
const failed = run.status === 'failed'
|
||||
const StatusIcon = failed ? XCircle : CheckCircle2
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'flex w-full items-start gap-3 border-b border-border px-3 py-2 text-left transition-colors hover:bg-accent',
|
||||
rowClassName,
|
||||
)}
|
||||
>
|
||||
<StatusIcon className={cn('mt-0.5 h-4 w-4 shrink-0', failed ? 'text-destructive' : 'text-success')} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<span className="truncate font-medium text-foreground">{run.jobName}</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{formatDistanceToNow(run.finishedAt ?? run.startedAt, { addSuffix: true })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="truncate text-xs text-muted-foreground">{run.repoName}</div>
|
||||
{run.preview && (
|
||||
<div className={cn('truncate text-xs', failed ? 'text-destructive/80' : 'text-muted-foreground')}>
|
||||
{run.preview}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
interface ScheduleReportsListProps {
|
||||
runs: UnreadScheduleRun[]
|
||||
total: number
|
||||
rowClassName?: string
|
||||
onMarkAllRead: () => void
|
||||
markAllPending: boolean
|
||||
onNavigate?: () => void
|
||||
showTitle?: boolean
|
||||
}
|
||||
|
||||
function ScheduleReportsList({ runs, total, rowClassName, onMarkAllRead, markAllPending, onNavigate, showTitle = true }: ScheduleReportsListProps) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
const openRun = (runId: number) => {
|
||||
onNavigate?.()
|
||||
navigate(`/schedules?scheduleTab=runs&runId=${runId}`)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-center justify-between gap-2 border-b border-border px-3 py-2">
|
||||
<div className="flex items-baseline gap-2">
|
||||
{showTitle && <span className="text-sm font-semibold text-foreground">Reports</span>}
|
||||
<span className="text-xs text-muted-foreground">{total} unread</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onMarkAllRead}
|
||||
disabled={total === 0 || markAllPending}
|
||||
className="text-xs font-medium text-primary transition-colors hover:underline disabled:pointer-events-none disabled:opacity-50"
|
||||
>
|
||||
Mark all read
|
||||
</button>
|
||||
</div>
|
||||
{runs.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-1 px-4 py-10 text-center">
|
||||
<CheckCircle2 className="h-6 w-6 text-success" />
|
||||
<p className="text-sm font-medium text-foreground">All caught up</p>
|
||||
<p className="text-xs text-muted-foreground">New scheduled reports will show up here.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-[60vh] overflow-y-auto">
|
||||
{runs.map((run) => (
|
||||
<ScheduleReportRow key={run.id} run={run} rowClassName={rowClassName} onClick={() => openRun(run.id)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Link
|
||||
to="/schedules?scheduleTab=runs"
|
||||
onClick={onNavigate}
|
||||
className="block border-t border-border px-3 py-2 text-center text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
All runs
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ScheduleReportsBell() {
|
||||
const isMobile = useMobile()
|
||||
const { data } = useUnreadScheduleRuns()
|
||||
const markAllViewed = useMarkAllScheduleRunsViewed()
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const runs = data?.runs ?? []
|
||||
const total = data?.total ?? 0
|
||||
const failed = data?.failed ?? 0
|
||||
|
||||
const markAllRead = () => {
|
||||
markAllViewed.mutate()
|
||||
}
|
||||
|
||||
const trigger = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={`Reports, ${total} unread`}
|
||||
onClick={isMobile ? () => setOpen(true) : undefined}
|
||||
className="relative h-8 w-8 text-muted-foreground transition-all duration-200 hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<Inbox className="h-4 w-4" />
|
||||
<ScheduleReportsCount total={total} failed={failed} />
|
||||
</Button>
|
||||
)
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<>
|
||||
{trigger}
|
||||
<BottomSheet isOpen={open} onClose={() => setOpen(false)} ariaLabel="Reports">
|
||||
<BottomSheetHeader title="Reports" />
|
||||
<BottomSheetContent className="px-0 pt-0">
|
||||
<ScheduleReportsList
|
||||
runs={runs}
|
||||
total={total}
|
||||
rowClassName="py-3"
|
||||
onMarkAllRead={markAllRead}
|
||||
markAllPending={markAllViewed.isPending}
|
||||
onNavigate={() => setOpen(false)}
|
||||
showTitle={false}
|
||||
/>
|
||||
</BottomSheetContent>
|
||||
</BottomSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-96 p-0">
|
||||
<ScheduleReportsList
|
||||
runs={runs}
|
||||
total={total}
|
||||
onMarkAllRead={markAllRead}
|
||||
markAllPending={markAllViewed.isPending}
|
||||
onNavigate={() => setOpen(false)}
|
||||
/>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { formatScheduleShortLabel, getJobStatusTone } from '@/components/schedules/schedule-utils'
|
||||
import { Bot, Clock3 } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface JobsTabProps {
|
||||
jobs: ScheduleJob[]
|
||||
selectedJobId: number | null
|
||||
onSelectJob: (id: number) => void
|
||||
}
|
||||
|
||||
export function JobsTab({ jobs, selectedJobId, onSelectJob }: JobsTabProps) {
|
||||
return (
|
||||
<div className="h-full overflow-y-auto space-y-2 pt-2">
|
||||
{jobs.map((job) => (
|
||||
<button
|
||||
key={job.id}
|
||||
type="button"
|
||||
onClick={() => onSelectJob(job.id)}
|
||||
className={cn(
|
||||
'w-full rounded-xl border-2 px-4 py-3 text-left transition-all',
|
||||
selectedJobId === job.id
|
||||
? 'border-primary bg-primary/10 ring-2 ring-primary/30'
|
||||
: 'border-border/70 bg-background/60 hover:bg-accent/40'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium truncate">{job.name}</p>
|
||||
<p className="mt-1 truncate text-xs text-muted-foreground">{job.description || 'No description yet'}</p>
|
||||
</div>
|
||||
<Badge className={getJobStatusTone(job)}>{job.enabled ? 'Enabled' : 'Paused'}</Badge>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-2 text-xs text-muted-foreground">
|
||||
<span className="inline-flex items-center gap-1"><Clock3 className="h-3.5 w-3.5" /> {formatScheduleShortLabel(job)}</span>
|
||||
<span className="inline-flex items-center gap-1"><Bot className="h-3.5 w-3.5" /> {job.agentSlug ?? 'default agent'}</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,12 +3,14 @@ import type { CreatePromptTemplateRequest } from '@opencode-manager/shared/types
|
||||
import type { PromptDialog } from '@/hooks/useScheduleUrlState'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Loader2, FileText, Plus, Upload } from 'lucide-react'
|
||||
import { Loader2, FileText, MoreHorizontal, Plus, Upload } from 'lucide-react'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
|
||||
import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates'
|
||||
import { parseMarkdownTemplate } from '@/lib/schedules/markdownTemplate'
|
||||
import { PromptTemplateDialog } from './PromptTemplateDialog'
|
||||
import { ScheduleListToolbar } from './ScheduleListToolbar'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { PromptTemplateCard } from './PromptTab'
|
||||
|
||||
interface PromptsTabProps {
|
||||
promptDialog: PromptDialog
|
||||
@@ -24,7 +26,15 @@ export function PromptsTab({ promptDialog, templateId, onNew, onEdit, onDelete,
|
||||
const [importValues, setImportValues] = useState<Partial<CreatePromptTemplateRequest> | undefined>()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const [search, setSearch] = useState('')
|
||||
const { data: templates = [], isLoading } = usePromptTemplates()
|
||||
const searchTerm = search.trim().toLowerCase()
|
||||
const visibleTemplates = searchTerm
|
||||
? templates.filter((template) =>
|
||||
[template.title, template.description, template.category, template.cadenceHint, template.suggestedName]
|
||||
.some((field) => field.toLowerCase().includes(searchTerm)),
|
||||
)
|
||||
: templates
|
||||
const deleteMutation = useDeletePromptTemplate()
|
||||
|
||||
const editingTemplate = templates.find((t) => t.id === templateId)
|
||||
@@ -72,31 +82,23 @@ export function PromptsTab({ promptDialog, templateId, onNew, onEdit, onDelete,
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col overflow-hidden">
|
||||
<div className="flex items-center justify-between gap-2 border-b border-border px-4 py-3">
|
||||
<h2 className="text-sm font-semibold">Prompt templates</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1 text-xs"
|
||||
onClick={onNew}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
New
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1 text-xs"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="h-3 w-3" />
|
||||
Import .md
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ScheduleListToolbar search={search} onSearchChange={setSearch} searchPlaceholder="Search prompts">
|
||||
<Button type="button" variant="outline" size="sm" className="h-9 shrink-0 gap-1" onClick={onNew}>
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">New</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9 shrink-0 gap-1"
|
||||
aria-label="Import .md"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">Import .md</span>
|
||||
</Button>
|
||||
</ScheduleListToolbar>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
@@ -106,12 +108,12 @@ export function PromptsTab({ promptDialog, templateId, onNew, onEdit, onDelete,
|
||||
onChange={handleFileImport}
|
||||
/>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : templates.length === 0 ? (
|
||||
) : visibleTemplates.length === 0 ? (
|
||||
<div className="flex min-h-full items-center justify-center">
|
||||
<Card className="max-w-md border-dashed border-border/70">
|
||||
<CardContent className="flex flex-col items-center gap-4 p-8 text-center">
|
||||
@@ -119,24 +121,88 @@ export function PromptsTab({ promptDialog, templateId, onNew, onEdit, onDelete,
|
||||
<FileText className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-lg font-semibold">No templates yet</p>
|
||||
<p className="text-lg font-semibold">{searchTerm ? 'No matching templates' : 'No templates yet'}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create prompt templates to reuse across your schedules.
|
||||
{searchTerm ? 'Try a different search.' : 'Create prompt templates to reuse across your schedules.'}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3 lg:grid-cols-2">
|
||||
{templates.map((template) => (
|
||||
<PromptTemplateCard
|
||||
key={template.id}
|
||||
template={template}
|
||||
onEdit={(item) => onEdit(item.id)}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
))}
|
||||
<div className="overflow-x-auto rounded-lg border border-border/70">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 z-10 whitespace-nowrap bg-background text-xs uppercase text-muted-foreground">
|
||||
<tr className="border-b border-border/60">
|
||||
<th scope="col" className="px-3 py-2.5 text-left font-medium">Template</th>
|
||||
<th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Category</th>
|
||||
<th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Cadence</th>
|
||||
<th scope="col" className="hidden px-3 py-2.5 text-left font-medium md:table-cell">Updated</th>
|
||||
<th scope="col" className="w-px px-3 py-2.5 text-right font-medium">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/60">
|
||||
{visibleTemplates.map((template) => (
|
||||
<tr
|
||||
key={template.id}
|
||||
tabIndex={0}
|
||||
onClick={() => onEdit(template.id)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.target !== event.currentTarget) return
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
onEdit(template.id)
|
||||
}
|
||||
}}
|
||||
className="cursor-pointer transition-colors hover:bg-accent/40"
|
||||
>
|
||||
<td className="px-3 py-2.5">
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="max-w-[32rem] truncate font-medium">{template.title}</span>
|
||||
{template.description && (
|
||||
<span className="max-w-[32rem] truncate text-xs text-muted-foreground">{template.description}</span>
|
||||
)}
|
||||
<span className="truncate text-xs text-muted-foreground sm:hidden">
|
||||
{template.category} · {template.cadenceHint}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="hidden px-3 py-2.5 text-muted-foreground sm:table-cell">
|
||||
<span className="capitalize">{template.category}</span>
|
||||
</td>
|
||||
<td className="hidden px-3 py-2.5 text-muted-foreground sm:table-cell">{template.cadenceHint}</td>
|
||||
<td
|
||||
className="hidden px-3 py-2.5 text-muted-foreground md:table-cell"
|
||||
title={new Date(template.updatedAt).toLocaleString()}
|
||||
>
|
||||
{formatDistanceToNow(template.updatedAt, { addSuffix: true })}
|
||||
</td>
|
||||
<td className="px-3 py-2.5 text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="More actions"
|
||||
className="h-7 w-7 text-muted-foreground"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" onClick={(event) => event.stopPropagation()}>
|
||||
<DropdownMenuItem onClick={() => onEdit(template.id)}>Edit</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => onDelete(template.id)}>
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -8,12 +8,17 @@ import type { ScheduleRun } from '@opencode-manager/shared/types'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getRepo: vi.fn(),
|
||||
useMarkScheduleRunViewed: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
getRepo: mocks.getRepo,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useMarkScheduleRunViewed: mocks.useMarkScheduleRunViewed,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
|
||||
FileBrowserSheet: ({ isOpen, initialSelectedFile }: { isOpen: boolean; initialSelectedFile?: string }) =>
|
||||
isOpen ? <div data-testid="file-browser-sheet" data-selected-file={initialSelectedFile} /> : null,
|
||||
@@ -37,6 +42,7 @@ const run: ScheduleRun = {
|
||||
status: 'completed',
|
||||
startedAt: 0,
|
||||
finishedAt: null,
|
||||
viewedAt: null,
|
||||
createdAt: 0,
|
||||
sessionId: null,
|
||||
sessionTitle: null,
|
||||
@@ -48,7 +54,7 @@ const run: ScheduleRun = {
|
||||
worktreePath: null,
|
||||
}
|
||||
|
||||
function renderPanel() {
|
||||
function renderPanel(activeRun: ScheduleRun | null = run) {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
@@ -60,7 +66,7 @@ function renderPanel() {
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RunDetailPanel
|
||||
repoId={5}
|
||||
activeRun={run}
|
||||
activeRun={activeRun}
|
||||
selectedRunLoading={false}
|
||||
onCancelRun={vi.fn()}
|
||||
cancelRunPending={false}
|
||||
@@ -80,6 +86,7 @@ function clickLink(name: string) {
|
||||
describe('RunDetailPanel local link handling', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useMarkScheduleRunViewed.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
})
|
||||
|
||||
it('prevents navigation and opens no sheet while the repo query is pending', async () => {
|
||||
@@ -127,4 +134,24 @@ describe('RunDetailPanel local link handling', () => {
|
||||
expect(docs.getAttribute('target')).toBe('_blank')
|
||||
expect(docs.getAttribute('rel')).toBe('noopener noreferrer')
|
||||
})
|
||||
|
||||
it('marks an unread completed run viewed and skips running or already-viewed runs', () => {
|
||||
const completedMutate = vi.fn()
|
||||
mocks.useMarkScheduleRunViewed.mockReturnValue({ mutate: completedMutate, isPending: false })
|
||||
const completed = renderPanel({ ...run, status: 'completed', viewedAt: null })
|
||||
expect(completedMutate).toHaveBeenCalledTimes(1)
|
||||
expect(completedMutate).toHaveBeenCalledWith(1)
|
||||
completed.unmount()
|
||||
|
||||
const runningMutate = vi.fn()
|
||||
mocks.useMarkScheduleRunViewed.mockReturnValue({ mutate: runningMutate, isPending: false })
|
||||
const running = renderPanel({ ...run, status: 'running', viewedAt: null })
|
||||
expect(runningMutate).not.toHaveBeenCalled()
|
||||
running.unmount()
|
||||
|
||||
const viewedMutate = vi.fn()
|
||||
mocks.useMarkScheduleRunViewed.mockReturnValue({ mutate: viewedMutate, isPending: false })
|
||||
renderPanel({ ...run, status: 'completed', viewedAt: 123 })
|
||||
expect(viewedMutate).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -9,6 +9,7 @@ import { getRepo } from '@/api/repos'
|
||||
import { getWorkspaceFilePath } from '@/lib/markdownLinks'
|
||||
import { getSessionPath } from '@/lib/navigation'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import { useMarkScheduleRunViewed } from '@/hooks/useSchedules'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import type { ScheduleRun } from '@opencode-manager/shared/types'
|
||||
|
||||
@@ -27,6 +28,21 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
|
||||
queryKey: ['repo', repoId],
|
||||
queryFn: () => getRepo(repoId),
|
||||
})
|
||||
const markRunViewed = useMarkScheduleRunViewed()
|
||||
const viewedRunIdRef = useRef<number | null>(null)
|
||||
|
||||
const activeRunId = activeRun?.id ?? null
|
||||
const activeRunStatus = activeRun?.status ?? null
|
||||
const activeRunViewedAt = activeRun?.viewedAt ?? null
|
||||
|
||||
useEffect(() => {
|
||||
if (activeRunId === null) return
|
||||
if (activeRunStatus !== 'completed' && activeRunStatus !== 'failed') return
|
||||
if (activeRunViewedAt !== null) return
|
||||
if (viewedRunIdRef.current === activeRunId) return
|
||||
viewedRunIdRef.current = activeRunId
|
||||
markRunViewed.mutate(activeRunId)
|
||||
}, [activeRunId, activeRunStatus, activeRunViewedAt, markRunViewed])
|
||||
|
||||
const handleOpenLocalPath = (linkPath: string) => {
|
||||
if (!repo) return
|
||||
@@ -54,30 +70,26 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
|
||||
return (
|
||||
<>
|
||||
<Tabs key={`${activeRun.id}-${String(activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log')}`} defaultValue={activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log'} className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div className="flex items-center justify-center gap-2 px-2 py-1.5">
|
||||
<div className="flex flex-shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3">
|
||||
<TabsList className="h-auto gap-0 rounded-none border-0 bg-transparent p-0">
|
||||
<TabsTrigger value="log" className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Log</TabsTrigger>
|
||||
<TabsTrigger value="response" disabled={!activeRun.responseText} className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Assistant Output</TabsTrigger>
|
||||
<TabsTrigger value="error" disabled={!activeRun.errorText} className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">{activeRun.status === 'cancelled' ? 'Details' : 'Error'}</TabsTrigger>
|
||||
<TabsTrigger value="log" className="rounded-none border-b-2 border-transparent px-3 py-2 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Log</TabsTrigger>
|
||||
<TabsTrigger value="response" disabled={!activeRun.responseText} className="rounded-none border-b-2 border-transparent px-3 py-2 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Assistant Output</TabsTrigger>
|
||||
<TabsTrigger value="error" disabled={!activeRun.errorText} className="rounded-none border-b-2 border-transparent px-3 py-2 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">{activeRun.status === 'cancelled' ? 'Details' : 'Error'}</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
{(activeRun.status === 'running' || activeRun.sessionId) && (
|
||||
<div className="flex items-center justify-between gap-2 px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{sessionId && (
|
||||
<Button variant="outline" size="sm" onClick={() => navigate(getSessionPath(repoId, sessionId))}>
|
||||
Open session
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 py-1">
|
||||
{sessionId && (
|
||||
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => navigate(getSessionPath(repoId, sessionId))}>
|
||||
Open session
|
||||
</Button>
|
||||
)}
|
||||
{activeRun.status === 'running' && (
|
||||
<Button variant="outline" size="sm" onClick={onCancelRun} disabled={cancelRunPending}>
|
||||
{cancelRunPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={onCancelRun} disabled={cancelRunPending}>
|
||||
{cancelRunPending ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : null}
|
||||
Cancel run
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<TabsContent value="log" className="mt-0 min-h-0 flex-1 overflow-y-auto px-3 py-3 xl:[mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{selectedRunLoading && !activeRun ? (
|
||||
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { History, Loader2, XCircle, CheckCircle2, Ban, ChevronDown, Trash2 } from 'lucide-react'
|
||||
import type { ScheduleRun } from '@opencode-manager/shared/types'
|
||||
import { getRunTone } from '@/components/schedules/schedule-utils'
|
||||
import { RunDetailPanel } from '@/components/schedules/RunDetailPanel'
|
||||
import { useRepoScheduleRun } from '@/hooks/useSchedules'
|
||||
|
||||
interface RunHistoryCardsProps {
|
||||
runs: ScheduleRun[] | undefined
|
||||
runsLoading: boolean
|
||||
selectedRunId?: number | null
|
||||
onSelectRun: (id: number) => void
|
||||
onCancelRun: () => void
|
||||
cancelRunPending: boolean
|
||||
onDeleteRun?: (runId: number) => void
|
||||
deleteRunPending?: boolean
|
||||
}
|
||||
|
||||
export function RunHistoryCards({
|
||||
runs,
|
||||
runsLoading,
|
||||
selectedRunId = null,
|
||||
onSelectRun,
|
||||
onCancelRun,
|
||||
cancelRunPending,
|
||||
onDeleteRun,
|
||||
deleteRunPending,
|
||||
}: RunHistoryCardsProps) {
|
||||
const [expandedRunId, setExpandedRunId] = useState<number | null>(selectedRunId)
|
||||
const [syncedSelectedRunId, setSyncedSelectedRunId] = useState<number | null>(selectedRunId)
|
||||
if (selectedRunId !== syncedSelectedRunId) {
|
||||
setSyncedSelectedRunId(selectedRunId)
|
||||
setExpandedRunId(selectedRunId)
|
||||
}
|
||||
const expandedRun = runs?.find((run) => run.id === expandedRunId)
|
||||
|
||||
const { data: runDetail, isLoading } = useRepoScheduleRun(
|
||||
expandedRun?.repoId,
|
||||
expandedRun?.jobId ?? null,
|
||||
expandedRun?.id ?? null
|
||||
)
|
||||
|
||||
function getRunStatusIcon(status: ScheduleRun['status']) {
|
||||
if (status === 'completed') return <CheckCircle2 className="h-3.5 w-3.5 text-success" />
|
||||
if (status === 'failed') return <XCircle className="h-3.5 w-3.5 text-destructive" />
|
||||
if (status === 'running') return <Loader2 className="h-3.5 w-3.5 animate-spin text-primary" />
|
||||
return <Ban className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
}
|
||||
|
||||
function handleCardClick(runId: number) {
|
||||
if (expandedRunId === runId) {
|
||||
setExpandedRunId(null)
|
||||
} else {
|
||||
setExpandedRunId(runId)
|
||||
onSelectRun(runId)
|
||||
}
|
||||
}
|
||||
|
||||
if (runsLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-6">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!runs?.length) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-6">
|
||||
<div className="text-center">
|
||||
<History className="h-10 w-10 text-muted-foreground mx-auto mb-4" />
|
||||
<p className="text-sm font-medium">No runs yet</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Use Run now to generate the first execution record and log bundle.</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
{runs.map((run) => {
|
||||
const isExpanded = expandedRunId === run.id
|
||||
const displayRun = isExpanded && runDetail ? runDetail : run
|
||||
|
||||
return (
|
||||
<div
|
||||
key={run.id}
|
||||
className="rounded-xl border border-border/70 overflow-hidden transition-all bg-card"
|
||||
>
|
||||
<div className="flex items-stretch">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCardClick(run.id)}
|
||||
className="min-w-0 flex-1 px-3 py-2 text-left flex items-center justify-between gap-2"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{getRunStatusIcon(run.status)}
|
||||
<Badge className={getRunTone(run)}>{run.status}</Badge>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">{run.triggerSource}</span>
|
||||
</div>
|
||||
<p className="mt-2 truncate text-sm font-medium leading-tight">
|
||||
{run.sessionTitle ?? 'No session recorded'}
|
||||
</p>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span>{new Date(run.startedAt).toLocaleString()}</span>
|
||||
{run.runBranch && (
|
||||
<>
|
||||
<span aria-hidden="true">•</span>
|
||||
<span className="font-mono">{run.runBranch}{run.commitHash ? ` @ ${run.commitHash.slice(0, 7)}` : ''}</span>
|
||||
</>
|
||||
)}
|
||||
{run.runBranch && !run.commitHash && run.status !== 'running' && (
|
||||
<>
|
||||
<span aria-hidden="true">•</span>
|
||||
<span className="italic">No changes committed</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{run.errorText && (
|
||||
<p className="mt-0.5 truncate text-xs text-destructive/80">{run.errorText}</p>
|
||||
)}
|
||||
</div>
|
||||
<ChevronDown className={`h-6 w-6 flex-shrink-0 text-muted-foreground transition-transform duration-200 self-start ${isExpanded ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
{onDeleteRun && run.status !== 'running' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDeleteRun(run.id)}
|
||||
disabled={deleteRunPending}
|
||||
title="Delete run"
|
||||
aria-label="Delete run"
|
||||
className="flex items-center px-2.5 text-muted-foreground transition-colors hover:text-destructive disabled:opacity-50"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{isExpanded && (
|
||||
<div className="border-t border-border/60 flex flex-col xl:max-h-[calc(100vh-200px)] xl:overflow-hidden">
|
||||
<RunDetailPanel
|
||||
repoId={run.repoId}
|
||||
activeRun={displayRun}
|
||||
selectedRunLoading={isExpanded && isLoading}
|
||||
onCancelRun={onCancelRun}
|
||||
cancelRunPending={cancelRunPending}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
import { useState } from 'react'
|
||||
import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { History, Loader2, Trash2 } from 'lucide-react'
|
||||
import { RunHistoryCards, RunDetailPanel } from '@/components/schedules'
|
||||
import { ScheduleListToolbar, ScheduleRunDrawer, ScheduleRunsTable } from '@/components/schedules'
|
||||
import { formatRunBranch, getRunStatusLabel, getRunTitle } from './schedule-run-display'
|
||||
|
||||
interface RunHistoryTabProps {
|
||||
repoId: number
|
||||
selectedJob: ScheduleJob | undefined
|
||||
runs: ScheduleRun[] | undefined
|
||||
runsLoading: boolean
|
||||
activeRun: ScheduleRun | null
|
||||
selectedRunLoading: boolean
|
||||
onSelectRun: (id: number) => void
|
||||
runId: number | null
|
||||
onSelectRun: (id: number | null) => void
|
||||
onCancelRun: () => void
|
||||
cancelRunPending: boolean
|
||||
onClearHistory: () => void
|
||||
@@ -21,13 +21,11 @@ interface RunHistoryTabProps {
|
||||
}
|
||||
|
||||
export function RunHistoryTab({
|
||||
repoId,
|
||||
selectedJob,
|
||||
runs,
|
||||
runsLoading,
|
||||
runId,
|
||||
onSelectRun,
|
||||
activeRun,
|
||||
selectedRunLoading,
|
||||
onCancelRun,
|
||||
cancelRunPending,
|
||||
onClearHistory,
|
||||
@@ -35,14 +33,9 @@ export function RunHistoryTab({
|
||||
onDeleteRun,
|
||||
deleteRunPending,
|
||||
}: RunHistoryTabProps) {
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
if (!selectedJob) {
|
||||
if (selectedRunLoading) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 h-full items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 h-full items-start">
|
||||
<Card className="max-w-3xl border-dashed border-border/70 w-full">
|
||||
@@ -56,43 +49,54 @@ export function RunHistoryTab({
|
||||
)
|
||||
}
|
||||
|
||||
const searchTerm = search.trim().toLowerCase()
|
||||
const runList = (runs ?? []).filter((run) => !searchTerm || [
|
||||
getRunTitle(run),
|
||||
getRunStatusLabel(run.status),
|
||||
run.triggerSource,
|
||||
formatRunBranch(run),
|
||||
run.errorText,
|
||||
].some((field) => field?.toLowerCase().includes(searchTerm)))
|
||||
const activeRun = runId !== null ? runList.find((run) => run.id === runId) ?? null : null
|
||||
const activeIndex = activeRun ? runList.findIndex((run) => run.id === activeRun.id) : -1
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div className="flex items-center justify-between gap-2 pt-2">
|
||||
<p className="text-sm font-medium text-muted-foreground">Run history</p>
|
||||
<ScheduleListToolbar search={search} onSearchChange={setSearch} searchPlaceholder="Search runs">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9 shrink-0"
|
||||
onClick={onClearHistory}
|
||||
disabled={clearHistoryPending || !runs?.length}
|
||||
aria-label="Clear history"
|
||||
>
|
||||
{clearHistoryPending ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
|
||||
Clear history
|
||||
<span className="hidden sm:inline">Clear history</span>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-hidden pt-2 xl:gap-4 xl:grid xl:grid-cols-[320px_minmax(0,1fr)] xl:grid-rows-1">
|
||||
<div className="min-h-0 h-full overflow-y-auto pb-2 xl:pr-1">
|
||||
<RunHistoryCards
|
||||
runs={runs}
|
||||
</ScheduleListToolbar>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto pt-2 pb-2">
|
||||
<div className="overflow-x-auto rounded-lg border border-border/70">
|
||||
<ScheduleRunsTable
|
||||
runs={runList}
|
||||
runsLoading={runsLoading}
|
||||
selectedRunId={runId}
|
||||
onSelectRun={onSelectRun}
|
||||
onCancelRun={onCancelRun}
|
||||
cancelRunPending={cancelRunPending}
|
||||
onDeleteRun={onDeleteRun}
|
||||
deleteRunPending={deleteRunPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="hidden xl:flex min-h-0 flex-col overflow-hidden rounded-xl border border-border/60 bg-background/60 py-3">
|
||||
<RunDetailPanel
|
||||
repoId={repoId}
|
||||
activeRun={activeRun}
|
||||
selectedRunLoading={selectedRunLoading}
|
||||
onCancelRun={onCancelRun}
|
||||
cancelRunPending={cancelRunPending}
|
||||
isFiltered={Boolean(searchTerm)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<ScheduleRunDrawer
|
||||
run={activeRun}
|
||||
open={runId !== null}
|
||||
onClose={() => onSelectRun(null)}
|
||||
onCancelRun={onCancelRun}
|
||||
cancelPending={cancelRunPending}
|
||||
onPrev={activeIndex > 0 ? () => onSelectRun(runList[activeIndex - 1].id) : undefined}
|
||||
onNext={activeIndex >= 0 && activeIndex < runList.length - 1 ? () => onSelectRun(runList[activeIndex + 1].id) : undefined}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import type { ComponentProps } from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { ScheduleJobsTable } from './ScheduleJobsTable'
|
||||
import type { ScheduleJobWithRepo, ScheduleRunSummary } from '@/api/schedules'
|
||||
|
||||
function makeJob(overrides: Partial<ScheduleJobWithRepo> = {}): ScheduleJobWithRepo {
|
||||
return {
|
||||
id: 1,
|
||||
repoId: 42,
|
||||
name: 'Weekly summary',
|
||||
description: 'Summarize the week',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Summarize the week',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
lastRunAt: null,
|
||||
nextRunAt: null,
|
||||
repoName: 'my-repo',
|
||||
repoPath: '/home/user/my-repo',
|
||||
repoUrl: 'https://example.com/my-repo',
|
||||
lastRun: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeRun(overrides: Partial<ScheduleRunSummary> = {}): ScheduleRunSummary {
|
||||
return {
|
||||
id: 9,
|
||||
status: 'completed',
|
||||
startedAt: Date.now() - 60_000,
|
||||
finishedAt: Date.now() - 30_000,
|
||||
viewedAt: Date.now(),
|
||||
preview: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function renderTable(jobs: ScheduleJobWithRepo[], props: Partial<ComponentProps<typeof ScheduleJobsTable>> = {}) {
|
||||
return render(
|
||||
<ScheduleJobsTable
|
||||
jobs={jobs}
|
||||
showRepo
|
||||
onOpen={vi.fn()}
|
||||
{...props}
|
||||
/>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('ScheduleJobsTable', () => {
|
||||
it('renders a semantic table with column headers', () => {
|
||||
renderTable([makeJob()])
|
||||
|
||||
expect(screen.getByRole('table')).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: 'Status' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: 'Job' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: 'Repo' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: 'Last result' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the NEW pill for an unread completed run', () => {
|
||||
renderTable([makeJob({ lastRun: makeRun({ status: 'completed', viewedAt: null }) })])
|
||||
|
||||
expect(screen.getAllByText('NEW').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('styles a failed preview with destructive text', () => {
|
||||
renderTable([makeJob({ lastRun: makeRun({ status: 'failed', viewedAt: 123, preview: 'Boom' }) })])
|
||||
|
||||
for (const preview of screen.getAllByText('Boom')) {
|
||||
expect(preview).toHaveClass('text-destructive/80')
|
||||
}
|
||||
})
|
||||
|
||||
it('shows a Cancel button for a running job', () => {
|
||||
renderTable(
|
||||
[makeJob({ lastRun: makeRun({ status: 'running', finishedAt: null, viewedAt: null }) })],
|
||||
{ onCancelRun: vi.fn() },
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Resume and the Paused label for a paused job', () => {
|
||||
renderTable([makeJob({ enabled: false })], { onToggleEnabled: vi.fn() })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Resume' })).toBeInTheDocument()
|
||||
expect(screen.getByText('Paused')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders only the provided actions in the menu with Delete last', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderTable([makeJob()], { onRunNow: vi.fn(), onEdit: vi.fn(), onDelete: vi.fn() })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'More actions' }))
|
||||
|
||||
const items = await screen.findAllByRole('menuitem')
|
||||
expect(items.map((item) => item.textContent)).toEqual(['Run now', 'Edit', 'Delete'])
|
||||
expect(items.at(-1)).toHaveClass('text-destructive')
|
||||
})
|
||||
|
||||
it('calls onOpen when a row is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onOpen = vi.fn()
|
||||
renderTable([makeJob()], { onOpen })
|
||||
|
||||
await user.click(screen.getByText('Weekly summary'))
|
||||
|
||||
expect(onOpen).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,259 @@
|
||||
import type { KeyboardEvent, MouseEvent } from 'react'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import { Loader2, MoreHorizontal } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { formatScheduleShortLabel, formatScheduleSummary } from './schedule-utils'
|
||||
import type { ScheduleJobWithRepo, ScheduleRunSummary } from '@/api/schedules'
|
||||
|
||||
interface ScheduleJobsTableProps {
|
||||
jobs: ScheduleJobWithRepo[]
|
||||
showRepo: boolean
|
||||
selectedJobId?: number | null
|
||||
onOpen: (job: ScheduleJobWithRepo) => void
|
||||
onRunNow?: (job: ScheduleJobWithRepo) => void
|
||||
onToggleEnabled?: (job: ScheduleJobWithRepo) => void
|
||||
onEdit?: (job: ScheduleJobWithRepo) => void
|
||||
onDelete?: (job: ScheduleJobWithRepo) => void
|
||||
onCancelRun?: (job: ScheduleJobWithRepo) => void
|
||||
onOpenJob?: (job: ScheduleJobWithRepo) => void
|
||||
onNavigateToRepo?: (repoPath: string) => void
|
||||
runPending?: boolean
|
||||
cancelPending?: boolean
|
||||
}
|
||||
|
||||
function isUnreadRun(lastRun: ScheduleRunSummary): boolean {
|
||||
return lastRun.viewedAt === null && (lastRun.status === 'completed' || lastRun.status === 'failed')
|
||||
}
|
||||
|
||||
function ScheduleJobNewPill() {
|
||||
return (
|
||||
<span className="shrink-0 rounded-full bg-primary/15 px-1.5 py-0.5 text-[10px] font-medium text-primary">
|
||||
NEW
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function ScheduleJobStatusIndicator({ job }: { job: ScheduleJobWithRepo }) {
|
||||
const status = job.lastRun?.status
|
||||
|
||||
if (status === 'running') {
|
||||
return <Loader2 aria-hidden="true" className="h-3.5 w-3.5 animate-spin text-primary" />
|
||||
}
|
||||
|
||||
if (status === 'completed') {
|
||||
return <span aria-hidden="true" className="h-2 w-2 rounded-full bg-success" />
|
||||
}
|
||||
|
||||
if (status === 'failed') {
|
||||
return <span aria-hidden="true" className="h-2 w-2 rounded-full bg-destructive" />
|
||||
}
|
||||
|
||||
return <span aria-hidden="true" className="h-2 w-2 rounded-full border border-muted-foreground/50" />
|
||||
}
|
||||
|
||||
function ScheduleJobLastResult({ lastRun }: { lastRun: ScheduleRunSummary | null }) {
|
||||
if (!lastRun) {
|
||||
return <span className="text-muted-foreground">No runs yet</span>
|
||||
}
|
||||
|
||||
if (lastRun.status === 'running') {
|
||||
return <span className="text-muted-foreground">Running · {formatDistanceToNow(lastRun.startedAt)}</span>
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
{formatDistanceToNow(lastRun.finishedAt ?? lastRun.startedAt, { addSuffix: true })}
|
||||
</span>
|
||||
{isUnreadRun(lastRun) && <ScheduleJobNewPill />}
|
||||
{lastRun.preview && (
|
||||
<span className={cn('hidden truncate sm:inline', lastRun.status === 'failed' ? 'text-destructive/80' : 'text-muted-foreground')}>
|
||||
{lastRun.preview}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export function ScheduleJobsTable({
|
||||
jobs,
|
||||
showRepo,
|
||||
selectedJobId = null,
|
||||
onOpen,
|
||||
onRunNow,
|
||||
onToggleEnabled,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onCancelRun,
|
||||
onOpenJob,
|
||||
onNavigateToRepo,
|
||||
runPending = false,
|
||||
cancelPending = false,
|
||||
}: ScheduleJobsTableProps) {
|
||||
const runAction = (action: ((target: ScheduleJobWithRepo) => void) | undefined, job: ScheduleJobWithRepo) => (event: MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
action?.(job)
|
||||
}
|
||||
|
||||
const handleKeyDown = (job: ScheduleJobWithRepo) => (event: KeyboardEvent<HTMLTableRowElement>) => {
|
||||
if (event.target !== event.currentTarget) return
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
onOpen(job)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 z-10 whitespace-nowrap bg-background text-xs uppercase text-muted-foreground">
|
||||
<tr className="border-b border-border/60">
|
||||
<th scope="col" className="px-3 py-2.5 text-left font-medium">Status</th>
|
||||
<th scope="col" className="px-3 py-2.5 text-left font-medium">Job</th>
|
||||
{showRepo && <th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Repo</th>}
|
||||
<th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Schedule</th>
|
||||
<th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Next run</th>
|
||||
<th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Last result</th>
|
||||
<th scope="col" className="w-px px-3 py-2.5 text-right font-medium">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/60">
|
||||
{jobs.map((job) => {
|
||||
const lastRun = job.lastRun
|
||||
const isRunning = lastRun?.status === 'running'
|
||||
const isPaused = !job.enabled
|
||||
const isSelected = selectedJobId === job.id
|
||||
const statusLabel = isRunning ? 'Running' : isPaused ? 'Paused' : 'Active'
|
||||
const nextRunLabel = !job.enabled || !job.nextRunAt
|
||||
? '—'
|
||||
: job.nextRunAt <= Date.now()
|
||||
? 'Due now'
|
||||
: formatDistanceToNow(job.nextRunAt, { addSuffix: true })
|
||||
const nextRunTitle = job.enabled && job.nextRunAt ? new Date(job.nextRunAt).toLocaleString() : undefined
|
||||
const scheduleLabel = formatScheduleShortLabel(job)
|
||||
const scheduleTitle = formatScheduleSummary(job)
|
||||
const mobileDetail = showRepo ? `${job.repoName} · ${scheduleLabel}` : scheduleLabel
|
||||
|
||||
const showRunNow = Boolean(onRunNow) && !isRunning
|
||||
const hasMenu = showRunNow || Boolean(onToggleEnabled) || Boolean(onEdit) || Boolean(onOpenJob) || Boolean(onDelete)
|
||||
|
||||
const contextualAction = isRunning && onCancelRun ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
onClick={runAction(onCancelRun, job)}
|
||||
disabled={cancelPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
) : isPaused && onToggleEnabled ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
onClick={runAction(onToggleEnabled, job)}
|
||||
>
|
||||
Resume
|
||||
</Button>
|
||||
) : null
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={job.id}
|
||||
tabIndex={0}
|
||||
onClick={() => onOpen(job)}
|
||||
onKeyDown={handleKeyDown(job)}
|
||||
className={cn(
|
||||
'cursor-pointer transition-colors hover:bg-accent/40',
|
||||
isPaused && 'opacity-60',
|
||||
isSelected && 'bg-accent/30',
|
||||
)}
|
||||
>
|
||||
<td className="px-3 py-2.5">
|
||||
<span className="flex items-center gap-2">
|
||||
<ScheduleJobStatusIndicator job={job} />
|
||||
<span className="hidden text-xs text-muted-foreground sm:inline">{statusLabel}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2.5">
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="max-w-[11rem] truncate font-medium sm:max-w-[20rem]">{job.name}</span>
|
||||
{job.description && <span className="max-w-[11rem] truncate text-xs text-muted-foreground sm:max-w-[20rem]">{job.description}</span>}
|
||||
<span className="max-w-[11rem] truncate text-xs text-muted-foreground sm:hidden" title={scheduleTitle}>{mobileDetail}</span>
|
||||
<span className="mt-0.5 text-xs sm:hidden">
|
||||
<ScheduleJobLastResult lastRun={lastRun} />
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
{showRepo && (
|
||||
<td className="hidden px-3 py-2.5 sm:table-cell">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onNavigateToRepo?.(job.repoPath)
|
||||
}}
|
||||
className="max-w-[16rem] truncate text-xs text-muted-foreground hover:text-foreground hover:underline"
|
||||
>
|
||||
{job.repoName}
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
<td className="hidden px-3 py-2.5 sm:table-cell">
|
||||
<span className="block truncate text-muted-foreground" title={scheduleTitle}>{scheduleLabel}</span>
|
||||
</td>
|
||||
<td className="hidden px-3 py-2.5 sm:table-cell">
|
||||
<span className="block truncate text-muted-foreground" title={nextRunTitle}>{nextRunLabel}</span>
|
||||
</td>
|
||||
<td className="hidden max-w-[16rem] px-3 py-2.5 sm:table-cell">
|
||||
<ScheduleJobLastResult lastRun={lastRun} />
|
||||
</td>
|
||||
<td className="px-3 py-2.5">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
{contextualAction}
|
||||
{hasMenu && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="More actions"
|
||||
className="h-7 w-7 text-muted-foreground"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" onClick={(event) => event.stopPropagation()}>
|
||||
{showRunNow && onRunNow && (
|
||||
<DropdownMenuItem disabled={runPending} onClick={runAction(onRunNow, job)}>Run now</DropdownMenuItem>
|
||||
)}
|
||||
{onToggleEnabled && (
|
||||
<DropdownMenuItem onClick={runAction(onToggleEnabled, job)}>
|
||||
{job.enabled ? 'Pause' : 'Resume'}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{onEdit && <DropdownMenuItem onClick={runAction(onEdit, job)}>Edit</DropdownMenuItem>}
|
||||
{onOpenJob && <DropdownMenuItem onClick={runAction(onOpenJob, job)}>Open job</DropdownMenuItem>}
|
||||
{onDelete && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive" onClick={runAction(onDelete, job)}>
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Search, X } from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
interface ScheduleListToolbarProps {
|
||||
search: string
|
||||
onSearchChange: (value: string) => void
|
||||
searchPlaceholder: string
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
export function ScheduleListToolbar({ search, onSearchChange, searchPlaceholder, children }: ScheduleListToolbarProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 pt-2 pb-1">
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<Search aria-hidden="true" className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(event) => onSearchChange(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape' && search) {
|
||||
event.stopPropagation()
|
||||
onSearchChange('')
|
||||
}
|
||||
}}
|
||||
placeholder={searchPlaceholder}
|
||||
aria-label={searchPlaceholder}
|
||||
className="h-9 pl-9 pr-8 [&::-webkit-search-cancel-button]:hidden"
|
||||
/>
|
||||
{search && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSearchChange('')}
|
||||
aria-label="Clear search"
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-0.5 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { ComponentProps } from 'react'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { ScheduleRunDrawer } from './ScheduleRunDrawer'
|
||||
import type { ScheduleRunWithContext } from '@/api/schedules'
|
||||
import type { Repo } from '@/api/types'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useRepoScheduleRun: vi.fn(),
|
||||
useMarkScheduleRunViewed: vi.fn(),
|
||||
getRepo: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useRepoScheduleRun: mocks.useRepoScheduleRun,
|
||||
useMarkScheduleRunViewed: mocks.useMarkScheduleRunViewed,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
getRepo: mocks.getRepo,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
|
||||
FileBrowserSheet: () => null,
|
||||
}))
|
||||
|
||||
const repo: Repo = {
|
||||
id: 5,
|
||||
name: 'my-repo',
|
||||
localPath: 'repos/my-repo',
|
||||
fullPath: '/abs/repos/my-repo',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 0,
|
||||
}
|
||||
|
||||
function makeRun(overrides: Partial<ScheduleRunWithContext> = {}): ScheduleRunWithContext {
|
||||
return {
|
||||
id: 1,
|
||||
jobId: 7,
|
||||
repoId: 5,
|
||||
triggerSource: 'manual',
|
||||
status: 'completed',
|
||||
startedAt: 0,
|
||||
finishedAt: 60_000,
|
||||
viewedAt: 123,
|
||||
createdAt: 0,
|
||||
sessionId: null,
|
||||
sessionTitle: null,
|
||||
logText: null,
|
||||
responseText: null,
|
||||
errorText: null,
|
||||
runBranch: 'feature/x',
|
||||
commitHash: 'abc1234def',
|
||||
worktreePath: null,
|
||||
jobName: 'Daily report',
|
||||
repoName: 'my-repo',
|
||||
repoPath: '/abs/repos/my-repo',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function renderDrawer(props: Partial<ComponentProps<typeof ScheduleRunDrawer>> = {}) {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ScheduleRunDrawer
|
||||
run={makeRun()}
|
||||
open
|
||||
onClose={vi.fn()}
|
||||
onCancelRun={vi.fn()}
|
||||
cancelPending={false}
|
||||
{...props}
|
||||
/>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('ScheduleRunDrawer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
|
||||
mocks.useMarkScheduleRunViewed.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
mocks.getRepo.mockResolvedValue(repo)
|
||||
})
|
||||
|
||||
it('renders the title and meta row', () => {
|
||||
renderDrawer()
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Daily report' })).toBeInTheDocument()
|
||||
expect(screen.getByText('Completed')).toBeInTheDocument()
|
||||
expect(screen.getByText('my-repo')).toBeInTheDocument()
|
||||
expect(screen.getByText('feature/x @ abc1234')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onNextUnread from the Next unread button', () => {
|
||||
const onNextUnread = vi.fn()
|
||||
renderDrawer({ onNextUnread, nextUnreadCount: 3 })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next unread (3)' }))
|
||||
|
||||
expect(onNextUnread).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('calls onClose when the close button is clicked', () => {
|
||||
const onClose = vi.fn()
|
||||
renderDrawer({ onClose })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('shows a not found message when no run is available', () => {
|
||||
renderDrawer({ run: null, open: true })
|
||||
|
||||
expect(screen.getByText('Run not found')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,131 @@
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { SideDrawer, SideDrawerContent, SideDrawerHeader } from '@/components/ui/side-drawer'
|
||||
import { RunDetailPanel } from './RunDetailPanel'
|
||||
import { formatRunBranch, getRunRepoName, getRunStatusIcon, getRunStatusLabel, getRunTitle, type ScheduleRunRow } from './schedule-run-display'
|
||||
import { formatRunDuration } from './schedule-utils'
|
||||
import { useRepoScheduleRun } from '@/hooks/useSchedules'
|
||||
|
||||
interface ScheduleRunDrawerProps {
|
||||
run: ScheduleRunRow | null
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onCancelRun: () => void
|
||||
cancelPending: boolean
|
||||
runLoading?: boolean
|
||||
runError?: boolean
|
||||
onRetry?: () => void
|
||||
onNextUnread?: () => void
|
||||
nextUnreadCount?: number
|
||||
onPrev?: () => void
|
||||
onNext?: () => void
|
||||
}
|
||||
|
||||
export function ScheduleRunDrawer({
|
||||
run,
|
||||
open,
|
||||
onClose,
|
||||
onCancelRun,
|
||||
cancelPending,
|
||||
runLoading = false,
|
||||
runError = false,
|
||||
onRetry,
|
||||
onNextUnread,
|
||||
nextUnreadCount = 0,
|
||||
onPrev,
|
||||
onNext,
|
||||
}: ScheduleRunDrawerProps) {
|
||||
const { data: detail, isLoading } = useRepoScheduleRun(run?.repoId, run?.jobId ?? null, run?.id ?? null)
|
||||
const activeRun = detail ?? run
|
||||
|
||||
const title = run ? getRunTitle(run) : 'Run'
|
||||
const repoName = run ? getRunRepoName(run) : null
|
||||
const branch = activeRun ? formatRunBranch(activeRun) : null
|
||||
const startedAt = activeRun ? activeRun.finishedAt ?? activeRun.startedAt : null
|
||||
|
||||
const meta = activeRun ? (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1.5">
|
||||
{getRunStatusIcon(activeRun.status)}
|
||||
<span>{getRunStatusLabel(activeRun.status)}</span>
|
||||
</span>
|
||||
{repoName && <span className="truncate">{repoName}</span>}
|
||||
{startedAt !== null && (
|
||||
<span title={new Date(startedAt).toLocaleString()}>
|
||||
{activeRun.status === 'running' ? 'Running' : formatDistanceToNow(startedAt, { addSuffix: true })}
|
||||
</span>
|
||||
)}
|
||||
<span className="tabular-nums">{formatRunDuration(activeRun)}</span>
|
||||
{branch && <span className="truncate font-mono">{branch}</span>}
|
||||
</div>
|
||||
) : undefined
|
||||
|
||||
const showNavigation = Boolean(onPrev || onNext)
|
||||
|
||||
return (
|
||||
<SideDrawer isOpen={open} onClose={onClose} side="right" widthClass="w-full sm:w-[min(880px,92vw)]" ariaLabel={title}>
|
||||
<SideDrawerHeader
|
||||
title={title}
|
||||
onClose={onClose}
|
||||
meta={meta}
|
||||
actions={(
|
||||
<>
|
||||
{onNextUnread && nextUnreadCount > 0 && (
|
||||
<Button variant="outline" size="sm" className="h-8" onClick={onNextUnread}>
|
||||
Next unread ({nextUnreadCount})
|
||||
</Button>
|
||||
)}
|
||||
{showNavigation && (
|
||||
<>
|
||||
<Button variant="ghost" size="icon-sm" aria-label="Previous run" onClick={onPrev} disabled={!onPrev}>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" aria-label="Next run" onClick={onNext} disabled={!onNext}>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
<SideDrawerContent className="flex min-h-0 flex-1 flex-col overflow-hidden p-0">
|
||||
{activeRun ? (
|
||||
<RunDetailPanel
|
||||
repoId={activeRun.repoId}
|
||||
activeRun={activeRun}
|
||||
selectedRunLoading={isLoading && !detail}
|
||||
onCancelRun={onCancelRun}
|
||||
cancelRunPending={cancelPending}
|
||||
/>
|
||||
) : runLoading ? (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : runError ? (
|
||||
<div className="flex h-full items-center justify-center p-6 text-center">
|
||||
<div className="space-y-3">
|
||||
<p className="text-lg font-semibold">Failed to load run</p>
|
||||
<p className="text-sm text-muted-foreground">The selected run could not be loaded.</p>
|
||||
{onRetry && (
|
||||
<Button variant="outline" onClick={onRetry}>
|
||||
Retry
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center p-6 text-center">
|
||||
<div className="space-y-3">
|
||||
<p className="text-lg font-semibold">Run not found</p>
|
||||
<p className="text-sm text-muted-foreground">The requested run no longer exists.</p>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</SideDrawerContent>
|
||||
</SideDrawer>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { ScheduleRunsTable } from './ScheduleRunsTable'
|
||||
import type { ScheduleRunWithContext } from '@/api/schedules'
|
||||
|
||||
function makeRun(overrides: Partial<ScheduleRunWithContext> = {}): ScheduleRunWithContext {
|
||||
return {
|
||||
id: 1,
|
||||
jobId: 7,
|
||||
repoId: 42,
|
||||
triggerSource: 'manual',
|
||||
status: 'completed',
|
||||
startedAt: Date.now() - 120_000,
|
||||
finishedAt: Date.now() - 60_000,
|
||||
viewedAt: 123,
|
||||
createdAt: Date.now() - 120_000,
|
||||
sessionId: 'ses-1',
|
||||
sessionTitle: 'Run title',
|
||||
logText: null,
|
||||
responseText: null,
|
||||
errorText: null,
|
||||
runBranch: null,
|
||||
commitHash: null,
|
||||
worktreePath: null,
|
||||
jobName: 'Weekly summary',
|
||||
repoName: 'my-repo',
|
||||
repoPath: '/home/user/my-repo',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('ScheduleRunsTable', () => {
|
||||
it('renders a row per run with the job name', () => {
|
||||
render(
|
||||
<ScheduleRunsTable
|
||||
runs={[makeRun({ id: 1, jobName: 'First job' }), makeRun({ id: 2, jobName: 'Second job' })]}
|
||||
runsLoading={false}
|
||||
selectedRunId={null}
|
||||
onSelectRun={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('table')).toBeInTheDocument()
|
||||
expect(screen.getByText('First job')).toBeInTheDocument()
|
||||
expect(screen.getByText('Second job')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the NEW pill for an unread run', () => {
|
||||
render(
|
||||
<ScheduleRunsTable
|
||||
runs={[makeRun({ status: 'completed', viewedAt: null })]}
|
||||
runsLoading={false}
|
||||
selectedRunId={null}
|
||||
onSelectRun={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('NEW')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onSelectRun when a row is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onSelectRun = vi.fn()
|
||||
render(
|
||||
<ScheduleRunsTable
|
||||
runs={[makeRun({ id: 42 })]}
|
||||
runsLoading={false}
|
||||
selectedRunId={null}
|
||||
onSelectRun={onSelectRun}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByText('Weekly summary'))
|
||||
|
||||
expect(onSelectRun).toHaveBeenCalledWith(42)
|
||||
})
|
||||
|
||||
it('hides the delete button for running runs', () => {
|
||||
render(
|
||||
<ScheduleRunsTable
|
||||
runs={[makeRun({ id: 1, status: 'running', finishedAt: null })]}
|
||||
runsLoading={false}
|
||||
selectedRunId={null}
|
||||
onSelectRun={vi.fn()}
|
||||
onDeleteRun={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Delete run' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the delete button for finished runs', () => {
|
||||
render(
|
||||
<ScheduleRunsTable
|
||||
runs={[makeRun({ id: 1, status: 'completed' })]}
|
||||
runsLoading={false}
|
||||
selectedRunId={null}
|
||||
onSelectRun={vi.fn()}
|
||||
onDeleteRun={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Delete run' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows an empty state when there are no runs', () => {
|
||||
render(
|
||||
<ScheduleRunsTable
|
||||
runs={[]}
|
||||
runsLoading={false}
|
||||
selectedRunId={null}
|
||||
onSelectRun={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('No runs yet')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,144 @@
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import { History, Loader2, Trash2 } from 'lucide-react'
|
||||
import { formatRunDuration } from '@/components/schedules/schedule-utils'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { formatRunBranch, getRunRepoName, getRunStatusIcon, getRunStatusLabel, getRunTitle, type ScheduleRunRow } from './schedule-run-display'
|
||||
|
||||
interface ScheduleRunsTableProps {
|
||||
runs: ScheduleRunRow[]
|
||||
runsLoading: boolean
|
||||
selectedRunId: number | null
|
||||
onSelectRun: (id: number) => void
|
||||
onDeleteRun?: (runId: number) => void
|
||||
deleteRunPending?: boolean
|
||||
isFiltered?: boolean
|
||||
}
|
||||
|
||||
export function ScheduleRunsTable({
|
||||
runs,
|
||||
runsLoading,
|
||||
selectedRunId,
|
||||
onSelectRun,
|
||||
onDeleteRun,
|
||||
deleteRunPending = false,
|
||||
isFiltered = false,
|
||||
}: ScheduleRunsTableProps) {
|
||||
const showRepo = runs.some((run) => getRunRepoName(run) !== null)
|
||||
|
||||
if (runsLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-6">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!runs.length) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-6">
|
||||
<div className="text-center">
|
||||
<History className="mx-auto mb-4 h-10 w-10 text-muted-foreground" />
|
||||
<p className="text-sm font-medium">{isFiltered ? 'No matching runs' : 'No runs yet'}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{isFiltered ? 'Try a different search or clear the filters.' : 'Use Run now to generate the first execution record and log bundle.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 z-10 whitespace-nowrap bg-background text-xs uppercase text-muted-foreground">
|
||||
<tr className="border-b border-border/60">
|
||||
<th scope="col" className="px-3 py-2.5 text-left font-medium">Status</th>
|
||||
<th scope="col" className="px-3 py-2.5 text-left font-medium">Run</th>
|
||||
{showRepo && <th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Repo</th>}
|
||||
<th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Trigger</th>
|
||||
<th scope="col" className="px-3 py-2.5 text-left font-medium">Started</th>
|
||||
<th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Duration</th>
|
||||
<th scope="col" className="hidden px-3 py-2.5 text-left font-medium sm:table-cell">Branch</th>
|
||||
<th scope="col" className="w-px px-3 py-2.5 text-right font-medium">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/60">
|
||||
{runs.map((run) => {
|
||||
const isUnread = run.viewedAt === null && (run.status === 'completed' || run.status === 'failed')
|
||||
const isSelected = selectedRunId === run.id
|
||||
const startedAt = run.finishedAt ?? run.startedAt
|
||||
const repoName = getRunRepoName(run)
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={run.id}
|
||||
tabIndex={0}
|
||||
onClick={() => onSelectRun(run.id)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.target !== event.currentTarget) return
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
onSelectRun(run.id)
|
||||
}
|
||||
}}
|
||||
className={cn('cursor-pointer transition-colors hover:bg-accent/40', isSelected && 'bg-accent/30')}
|
||||
>
|
||||
<td className="px-3 py-2.5">
|
||||
<span className="flex items-center gap-2">
|
||||
{getRunStatusIcon(run.status)}
|
||||
<span className="hidden text-xs text-muted-foreground sm:inline">{getRunStatusLabel(run.status)}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2.5">
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<span className={cn('truncate', isUnread ? 'font-semibold' : 'font-medium')}>{getRunTitle(run)}</span>
|
||||
{isUnread && (
|
||||
<span className="shrink-0 rounded-full bg-primary/15 px-1.5 py-0.5 text-[10px] font-medium text-primary">NEW</span>
|
||||
)}
|
||||
</span>
|
||||
{run.errorText && (
|
||||
<span className={cn('truncate text-xs', run.status === 'cancelled' ? 'text-muted-foreground' : 'text-destructive/80')}>
|
||||
{run.errorText}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
{showRepo && (
|
||||
<td className="hidden px-3 py-2.5 sm:table-cell">
|
||||
<span className="block max-w-[16rem] truncate text-xs text-muted-foreground">{repoName}</span>
|
||||
</td>
|
||||
)}
|
||||
<td className="hidden px-3 py-2.5 capitalize text-muted-foreground sm:table-cell">{run.triggerSource}</td>
|
||||
<td className="px-3 py-2.5">
|
||||
<span className="text-muted-foreground" title={new Date(startedAt).toLocaleString()}>
|
||||
{run.status === 'running' ? 'Running' : formatDistanceToNow(startedAt, { addSuffix: true })}
|
||||
</span>
|
||||
</td>
|
||||
<td className="hidden px-3 py-2.5 tabular-nums text-muted-foreground sm:table-cell">{formatRunDuration(run)}</td>
|
||||
<td className="hidden px-3 py-2.5 font-mono text-xs text-muted-foreground sm:table-cell">{formatRunBranch(run) ?? '—'}</td>
|
||||
<td className="px-3 py-2.5">
|
||||
<div className="flex items-center justify-end">
|
||||
{onDeleteRun && run.status !== 'running' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onDeleteRun(run.id)
|
||||
}}
|
||||
disabled={deleteRunPending}
|
||||
title="Delete run"
|
||||
aria-label="Delete run"
|
||||
className="flex items-center p-1.5 text-muted-foreground transition-colors hover:text-destructive disabled:opacity-50"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
@@ -73,6 +73,22 @@ describe('PromptsTab', () => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('filters templates by search and shows an empty match state', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<PromptsTab {...createProps()} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.type(screen.getByRole('searchbox', { name: 'Search prompts' }), 'health')
|
||||
expect(screen.getByText('Weekly Health Report')).toBeInTheDocument()
|
||||
|
||||
await user.clear(screen.getByRole('searchbox', { name: 'Search prompts' }))
|
||||
await user.type(screen.getByRole('searchbox', { name: 'Search prompts' }), 'nothing here')
|
||||
expect(screen.queryByText('Weekly Health Report')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('No matching templates')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Clear search' }))
|
||||
expect(screen.getByText('Weekly Health Report')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the sample template title', () => {
|
||||
render(<PromptsTab {...createProps()} />, { wrapper: createWrapper() })
|
||||
expect(screen.getByText('Weekly Health Report')).toBeInTheDocument()
|
||||
@@ -88,16 +104,13 @@ describe('PromptsTab', () => {
|
||||
expect(onNew).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('calls onDelete when the delete button on a template card is clicked', async () => {
|
||||
it('calls onDelete from the row actions menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onDelete = vi.fn()
|
||||
const { container } = render(<PromptsTab {...createProps({ onDelete })} />, {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
render(<PromptsTab {...createProps({ onDelete })} />, { wrapper: createWrapper() })
|
||||
|
||||
const deleteButton = container.querySelector('.lucide-trash2')?.closest('button')
|
||||
expect(deleteButton).toBeTruthy()
|
||||
await user.click(deleteButton!)
|
||||
await user.click(screen.getByRole('button', { name: 'More actions' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: 'Delete' }))
|
||||
expect(onDelete).toHaveBeenCalledWith(sampleTemplate.id)
|
||||
})
|
||||
|
||||
@@ -117,16 +130,12 @@ describe('PromptsTab', () => {
|
||||
expect(mocks.deleteMutate).toHaveBeenCalledWith(sampleTemplate.id, expect.any(Object))
|
||||
})
|
||||
|
||||
it('calls onEdit when the edit button on a template card is clicked', async () => {
|
||||
it('calls onEdit when a template row is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onEdit = vi.fn()
|
||||
const { container } = render(<PromptsTab {...createProps({ onEdit })} />, {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
render(<PromptsTab {...createProps({ onEdit })} />, { wrapper: createWrapper() })
|
||||
|
||||
const editButton = container.querySelector('.lucide-pencil')?.closest('button')
|
||||
expect(editButton).toBeTruthy()
|
||||
await user.click(editButton!)
|
||||
await user.click(screen.getByText('Weekly Health Report'))
|
||||
expect(onEdit).toHaveBeenCalledWith(sampleTemplate.id)
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatRunDuration, matchesScheduleJobSearch } from '@/components/schedules/schedule-utils'
|
||||
import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||
|
||||
describe('formatRunDuration', () => {
|
||||
it('formats seconds, minutes, and hours', () => {
|
||||
expect(formatRunDuration({ startedAt: 0, finishedAt: 45_000 })).toBe('45s')
|
||||
expect(formatRunDuration({ startedAt: 0, finishedAt: 192_000 })).toBe('3m 12s')
|
||||
expect(formatRunDuration({ startedAt: 0, finishedAt: 3_840_000 })).toBe('1h 4m')
|
||||
})
|
||||
|
||||
it('measures running runs against now', () => {
|
||||
expect(formatRunDuration({ startedAt: 1_000, finishedAt: null }, 31_000)).toBe('30s')
|
||||
})
|
||||
})
|
||||
|
||||
describe('matchesScheduleJobSearch', () => {
|
||||
const job = { name: 'Docs drift review', description: 'Check README drift', repoName: 'vllm' } as ScheduleJob & { repoName: string }
|
||||
|
||||
it('matches name, description, and repo case-insensitively', () => {
|
||||
expect(matchesScheduleJobSearch(job, 'DRIFT')).toBe(true)
|
||||
expect(matchesScheduleJobSearch(job, 'readme')).toBe(true)
|
||||
expect(matchesScheduleJobSearch(job, 'vllm')).toBe(true)
|
||||
expect(matchesScheduleJobSearch(job, 'triage')).toBe(false)
|
||||
})
|
||||
|
||||
it('matches everything for a blank term', () => {
|
||||
expect(matchesScheduleJobSearch(job, ' ')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,11 @@
|
||||
export { JobsTab } from './JobsTab'
|
||||
export { ScheduleJobsTable } from './ScheduleJobsTable'
|
||||
export { JobDetailTab } from './JobDetailTab'
|
||||
export { RunHistoryTab } from './RunHistoryTab'
|
||||
export { RunHistoryCards } from './RunHistoryCards'
|
||||
export { ScheduleRunDrawer } from './ScheduleRunDrawer'
|
||||
export { ScheduleRunsTable } from './ScheduleRunsTable'
|
||||
export { RunDetailPanel } from './RunDetailPanel'
|
||||
export { ScheduleJobDialog } from './ScheduleJobDialog'
|
||||
export { ScheduleRunMarkdown } from './ScheduleRunMarkdown'
|
||||
export { ScheduleTabMenu } from './ScheduleTabMenu'
|
||||
export { PromptsTab } from './PromptsTab'
|
||||
export { ScheduleListToolbar } from './ScheduleListToolbar'
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Ban, CheckCircle2, Loader2, XCircle } from 'lucide-react'
|
||||
import type { ScheduleRun } from '@opencode-manager/shared/types'
|
||||
import type { ScheduleRunWithContext } from '@/api/schedules'
|
||||
|
||||
export type ScheduleRunRow = ScheduleRun | ScheduleRunWithContext
|
||||
|
||||
export function getRunStatusIcon(status: ScheduleRun['status']) {
|
||||
if (status === 'completed') return <CheckCircle2 aria-hidden="true" className="h-3.5 w-3.5 text-success" />
|
||||
if (status === 'failed') return <XCircle aria-hidden="true" className="h-3.5 w-3.5 text-destructive" />
|
||||
if (status === 'running') return <Loader2 aria-hidden="true" className="h-3.5 w-3.5 animate-spin text-primary" />
|
||||
return <Ban aria-hidden="true" className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
}
|
||||
|
||||
export function getRunStatusLabel(status: ScheduleRun['status']) {
|
||||
if (status === 'completed') return 'Completed'
|
||||
if (status === 'failed') return 'Failed'
|
||||
if (status === 'running') return 'Running'
|
||||
return 'Cancelled'
|
||||
}
|
||||
|
||||
export function getRunTitle(run: ScheduleRunRow): string {
|
||||
if ('jobName' in run && typeof run.jobName === 'string') return run.jobName
|
||||
return run.sessionTitle ?? 'No session recorded'
|
||||
}
|
||||
|
||||
export function getRunRepoName(run: ScheduleRunRow): string | null {
|
||||
return 'repoName' in run && typeof run.repoName === 'string' ? run.repoName : null
|
||||
}
|
||||
|
||||
export function formatRunBranch(run: ScheduleRunRow): string | null {
|
||||
if (!run.runBranch) return null
|
||||
return `${run.runBranch}${run.commitHash ? ` @ ${run.commitHash.slice(0, 7)}` : ''}`
|
||||
}
|
||||
@@ -263,7 +263,7 @@ export function formatScheduleSummary(job: ScheduleJob): string {
|
||||
|
||||
export function formatScheduleShortLabel(job: ScheduleJob): string {
|
||||
if (job.scheduleMode === 'cron') {
|
||||
return 'Cron schedule'
|
||||
return formatCronHumanText(job.cronExpression) ?? 'Custom cron'
|
||||
}
|
||||
|
||||
return formatIntervalLabel(job.intervalMinutes)
|
||||
@@ -321,20 +321,15 @@ export function formatTimestamp(value: number | null): string {
|
||||
return `${new Date(value).toLocaleString()} (${formatDistanceToNow(value, { addSuffix: true })})`
|
||||
}
|
||||
|
||||
export function getRunTone(run: ScheduleRun): string {
|
||||
if (run.status === 'completed') {
|
||||
return 'bg-success/15 text-success border-success/30'
|
||||
}
|
||||
export function formatRunDuration(run: Pick<ScheduleRun, 'startedAt' | 'finishedAt'>, now: number = Date.now()): string {
|
||||
const totalSeconds = Math.max(0, Math.round(((run.finishedAt ?? now) - run.startedAt) / 1000))
|
||||
const hours = Math.floor(totalSeconds / 3600)
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
||||
const seconds = totalSeconds % 60
|
||||
|
||||
if (run.status === 'failed') {
|
||||
return 'bg-destructive/15 text-destructive border-destructive/30'
|
||||
}
|
||||
|
||||
if (run.status === 'cancelled') {
|
||||
return 'bg-muted text-muted-foreground border-border'
|
||||
}
|
||||
|
||||
return 'bg-warning/15 text-warning border-warning/30'
|
||||
if (hours > 0) return `${hours}h ${minutes}m`
|
||||
if (minutes > 0) return `${minutes}m ${seconds}s`
|
||||
return `${seconds}s`
|
||||
}
|
||||
|
||||
export function getJobStatusTone(job: ScheduleJob): string {
|
||||
@@ -350,3 +345,9 @@ export function hasSkillMetadata(job?: ScheduleJob | null): boolean {
|
||||
|
||||
return job.skillMetadata.skillSlugs.length > 0 || Boolean(job.skillMetadata.notes?.trim())
|
||||
}
|
||||
|
||||
export function matchesScheduleJobSearch(job: ScheduleJob & { repoName?: string }, searchTerm: string): boolean {
|
||||
const term = searchTerm.trim().toLowerCase()
|
||||
if (!term) return true
|
||||
return [job.name, job.description, job.repoName].some((field) => field?.toLowerCase().includes(term))
|
||||
}
|
||||
@@ -88,15 +88,17 @@ export interface SideDrawerHeaderProps {
|
||||
title: string
|
||||
onClose: () => void
|
||||
meta?: React.ReactNode
|
||||
actions?: React.ReactNode
|
||||
}
|
||||
|
||||
export function SideDrawerHeader({ title, onClose, meta }: SideDrawerHeaderProps) {
|
||||
export function SideDrawerHeader({ title, onClose, meta, actions }: SideDrawerHeaderProps) {
|
||||
return (
|
||||
<div className="flex-shrink-0 border-b border-border bg-background px-4 py-2 flex items-center justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="text-lg font-semibold text-foreground leading-none">{title}</h2>
|
||||
{meta ? <div className="mt-1 min-w-0">{meta}</div> : null}
|
||||
</div>
|
||||
{actions ? <div className="flex shrink-0 items-center gap-1">{actions}</div> : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
/** Returns `value` once it has stopped changing for `delayMs` milliseconds. */
|
||||
export function useDebouncedValue<T>(value: T, delayMs: number = 300): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState(value)
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedValue(value), delayMs)
|
||||
return () => clearTimeout(timer)
|
||||
}, [value, delayMs])
|
||||
|
||||
return debouncedValue
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
|
||||
import { findFiles } from '@/api/opencode'
|
||||
|
||||
export interface FileSearchResult {
|
||||
@@ -13,12 +13,7 @@ export function useFileSearch(
|
||||
enabled: boolean = true,
|
||||
directory?: string
|
||||
): FileSearchResult {
|
||||
const [debouncedQuery, setDebouncedQuery] = useState(query)
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedQuery(query), 300)
|
||||
return () => clearTimeout(timer)
|
||||
}, [query])
|
||||
const debouncedQuery = useDebouncedValue(query, 300)
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['file-search', debouncedQuery, directory],
|
||||
|
||||
@@ -11,13 +11,17 @@ import {
|
||||
listAllScheduleRuns,
|
||||
listAllSchedules,
|
||||
listRepoScheduleRuns,
|
||||
listRepoSchedules,
|
||||
listUnreadScheduleRuns,
|
||||
markAllScheduleRunsViewed,
|
||||
markScheduleRunViewed,
|
||||
runRepoSchedule,
|
||||
updateRepoSchedule,
|
||||
} from '@/api/schedules'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import type { ListAllRunsParams, ScheduleJobWithRepo, ScheduleRunWithContext } from '@/api/schedules'
|
||||
|
||||
export const UNREAD_SCHEDULE_RUNS_QUERY_KEY = ['schedule-runs-unread'] as const
|
||||
|
||||
export function useAllSchedules() {
|
||||
return useQuery({
|
||||
queryKey: ['all-schedules'],
|
||||
@@ -25,6 +29,7 @@ export function useAllSchedules() {
|
||||
const response = await listAllSchedules()
|
||||
return response.jobs as ScheduleJobWithRepo[]
|
||||
},
|
||||
refetchInterval: 10000,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -40,15 +45,39 @@ export function useAllScheduleRuns(params: ListAllRunsParams, enabled: boolean =
|
||||
})
|
||||
}
|
||||
|
||||
export function useRepoSchedules(repoId: number | undefined) {
|
||||
export function useUnreadScheduleRuns() {
|
||||
return useQuery({
|
||||
queryKey: ['repo-schedules', repoId],
|
||||
queryFn: async () => {
|
||||
const response = await listRepoSchedules(repoId!)
|
||||
return response.jobs
|
||||
queryKey: UNREAD_SCHEDULE_RUNS_QUERY_KEY,
|
||||
queryFn: () => listUnreadScheduleRuns(),
|
||||
refetchInterval: 10000,
|
||||
refetchOnWindowFocus: true,
|
||||
})
|
||||
}
|
||||
|
||||
export function useMarkScheduleRunViewed() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (runId: number) => markScheduleRunViewed(runId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: UNREAD_SCHEDULE_RUNS_QUERY_KEY })
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useMarkAllScheduleRunsViewed() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: () => markAllScheduleRunsViewed(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: UNREAD_SCHEDULE_RUNS_QUERY_KEY })
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
|
||||
showToast.success('All reports marked as read')
|
||||
},
|
||||
enabled: repoId !== undefined,
|
||||
refetchInterval: 5000,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
import { useState, useMemo, useEffect, useRef } from 'react'
|
||||
import { useState, useMemo, useEffect, useRef, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useAllSchedules, useAllScheduleRuns, useCancelRepoScheduleRun } from '@/hooks/useSchedules'
|
||||
import { useAllSchedules, useAllScheduleRuns, useCancelRepoScheduleRun, useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { useDeleteRepoSchedule, useRunRepoSchedule, useUpdateRepoSchedule, useCreateRepoSchedule } from '@/hooks/useSchedules'
|
||||
import { ScheduleJobDialog, RunHistoryCards, PromptsTab } from '@/components/schedules'
|
||||
import { ScheduleJobDialog, PromptsTab, ScheduleJobsTable, ScheduleListToolbar, ScheduleRunDrawer, ScheduleRunsTable } from '@/components/schedules'
|
||||
import type { CreateScheduleJobRequest } from '@opencode-manager/shared/types'
|
||||
import { toUpdateScheduleRequest, formatScheduleShortLabel, formatTimestamp, getJobStatusTone } from '@/components/schedules/schedule-utils'
|
||||
import { matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
|
||||
import { Header } from '@/components/ui/header'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScheduleReportsBell } from '@/components/notifications/ScheduleReportsBell'
|
||||
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuCheckboxItem, DropdownMenuItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
|
||||
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, XCircle, SearchX } from 'lucide-react'
|
||||
import { CalendarClock, Loader2, Plus, ArrowLeft, SlidersHorizontal } from 'lucide-react'
|
||||
|
||||
import { useScheduleUrlState } from '@/hooks/useScheduleUrlState'
|
||||
import type { ScheduleTab } from '@/hooks/useScheduleUrlState'
|
||||
import { useSidebarAction } from '@/hooks/useSidebarAction'
|
||||
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
|
||||
|
||||
import type { ScheduleJobWithRepo, ScheduleRunWithContext } from '@/api/schedules'
|
||||
import { Combobox } from '@/components/ui/combobox'
|
||||
@@ -33,6 +34,9 @@ export function GlobalSchedules() {
|
||||
const [scheduleModeFilter, setScheduleModeFilter] = useState<ScheduleModeFilter>('all')
|
||||
const [repoFilter, setRepoFilter] = useState<string>('all')
|
||||
const [sortOption, setSortOption] = useState<SortOption>('nextRun')
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [runSearch, setRunSearch] = useState('')
|
||||
const debouncedRunSearch = useDebouncedValue(runSearch.trim(), 300)
|
||||
const [runStatusFilter, setRunStatusFilter] = useState<string>('all')
|
||||
const [runRepoFilter, setRunRepoFilter] = useState<string>('all')
|
||||
const [runTriggerFilter, setRunTriggerFilter] = useState<string>('all')
|
||||
@@ -66,7 +70,8 @@ export function GlobalSchedules() {
|
||||
status: runStatusFilter !== 'all' ? runStatusFilter : undefined,
|
||||
repoId: runRepoFilter !== 'all' ? Number(runRepoFilter.split('|')[0]) : undefined,
|
||||
triggerSource: runTriggerFilter !== 'all' ? runTriggerFilter : undefined,
|
||||
}), [runStatusFilter, runRepoFilter, runTriggerFilter, runOffset])
|
||||
search: debouncedRunSearch || undefined,
|
||||
}), [runStatusFilter, runRepoFilter, runTriggerFilter, runOffset, debouncedRunSearch])
|
||||
|
||||
const { data: runsPage = [], isLoading: runsLoading } = useAllScheduleRuns(runsParams, scheduleTab === 'runs')
|
||||
|
||||
@@ -84,13 +89,35 @@ export function GlobalSchedules() {
|
||||
refetch: refetchSelectedRun,
|
||||
} = useAllScheduleRuns(
|
||||
selectedRunParams,
|
||||
scheduleTab === 'runs' && runId !== null && selectedRunInHistory === null,
|
||||
runId !== null && selectedRunInHistory === null,
|
||||
)
|
||||
|
||||
const selectedRun = runId === null
|
||||
? null
|
||||
: selectedRunInHistory ?? selectedRunPage?.[0] ?? null
|
||||
|
||||
const { data: unreadRuns } = useUnreadScheduleRuns()
|
||||
const unreadTotal = unreadRuns?.total ?? 0
|
||||
const nextUnreadRun = unreadRuns?.runs.find((run) => run.id !== runId) ?? unreadRuns?.runs[0] ?? null
|
||||
|
||||
const handleNextUnread = useCallback(() => {
|
||||
if (!nextUnreadRun) return
|
||||
selectRun(nextUnreadRun.id)
|
||||
}, [nextUnreadRun, selectRun])
|
||||
|
||||
useEffect(() => {
|
||||
if (scheduleTab !== 'runs' && runId === null) return
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'u') return
|
||||
const target = event.target as HTMLElement | null
|
||||
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return
|
||||
event.preventDefault()
|
||||
handleNextUnread()
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [scheduleTab, runId, handleNextUnread])
|
||||
|
||||
const createMutation = useCreateRepoSchedule()
|
||||
const deleteMutation = useDeleteRepoSchedule()
|
||||
const runMutation = useRunRepoSchedule()
|
||||
@@ -99,7 +126,7 @@ export function GlobalSchedules() {
|
||||
useEffect(() => {
|
||||
setRunOffset(0)
|
||||
setAllRuns([])
|
||||
}, [runStatusFilter, runRepoFilter, runTriggerFilter])
|
||||
}, [runStatusFilter, runRepoFilter, runTriggerFilter, debouncedRunSearch])
|
||||
|
||||
useEffect(() => {
|
||||
if (runsPage.length > 0) {
|
||||
@@ -174,6 +201,8 @@ export function GlobalSchedules() {
|
||||
filtered = filtered.filter((job) => job.repoPath === repoFilter)
|
||||
}
|
||||
|
||||
filtered = filtered.filter((job) => matchesScheduleJobSearch(job, searchQuery))
|
||||
|
||||
filtered.sort((a, b) => {
|
||||
switch (sortOption) {
|
||||
case 'name':
|
||||
@@ -190,7 +219,7 @@ export function GlobalSchedules() {
|
||||
})
|
||||
|
||||
return filtered
|
||||
}, [jobs, statusFilter, scheduleModeFilter, repoFilter, sortOption])
|
||||
}, [jobs, statusFilter, scheduleModeFilter, repoFilter, sortOption, searchQuery])
|
||||
|
||||
const repoOptions = useMemo(() => [
|
||||
{ value: 'all', label: 'All Repos', description: `${jobs.length} total jobs` },
|
||||
@@ -314,6 +343,37 @@ export function GlobalSchedules() {
|
||||
navigate(getRepoPath(repoId))
|
||||
}
|
||||
|
||||
const handleOpenJobPage = (job: ScheduleJobWithRepo) => {
|
||||
navigate(`/repos/${job.repoId}/schedules`)
|
||||
}
|
||||
|
||||
const handleOpenJobRow = (job: ScheduleJobWithRepo) => {
|
||||
const lastRun = job.lastRun
|
||||
if (lastRun) {
|
||||
selectRun(lastRun.id)
|
||||
return
|
||||
}
|
||||
handleOpenJobPage(job)
|
||||
}
|
||||
|
||||
const handleCancelJobRun = (job: ScheduleJobWithRepo) => {
|
||||
if (!job.lastRun) return
|
||||
handleCancelRun(job.repoId, job.id, job.lastRun.id)
|
||||
}
|
||||
|
||||
const handleCancelSelectedRun = () => {
|
||||
if (!selectedRun) return
|
||||
handleCancelRun(selectedRun.repoId, selectedRun.jobId, selectedRun.id)
|
||||
}
|
||||
|
||||
const selectedRunIndex = runId !== null ? sortedRuns.findIndex((run) => run.id === runId) : -1
|
||||
const selectedRunPrev = scheduleTab === 'runs' && selectedRunIndex > 0
|
||||
? () => selectRun(sortedRuns[selectedRunIndex - 1].id)
|
||||
: undefined
|
||||
const selectedRunNext = scheduleTab === 'runs' && selectedRunIndex >= 0 && selectedRunIndex < sortedRuns.length - 1
|
||||
? () => selectRun(sortedRuns[selectedRunIndex + 1].id)
|
||||
: undefined
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-background">
|
||||
@@ -343,7 +403,6 @@ export function GlobalSchedules() {
|
||||
const selectedRunMissing = runId !== null && selectedRunInHistory === null
|
||||
const selectedRunLookupLoading = selectedRunMissing && selectedRunLoading
|
||||
const selectedRunLookupError = selectedRunMissing && selectedRunError && selectedRun === null
|
||||
const selectedRunLookupNotFound = selectedRunMissing && !selectedRunLoading && !selectedRunError && selectedRun === null
|
||||
|
||||
return (
|
||||
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col">
|
||||
@@ -352,6 +411,7 @@ export function GlobalSchedules() {
|
||||
<Header.Title>Schedules</Header.Title>
|
||||
<div className="flex items-center gap-2">
|
||||
<Header.Actions>
|
||||
<ScheduleReportsBell />
|
||||
<Button
|
||||
onClick={() => { openNewJob(); setSelectedRepoId(undefined) }}
|
||||
size="sm"
|
||||
@@ -388,19 +448,18 @@ export function GlobalSchedules() {
|
||||
</div>
|
||||
|
||||
<TabsContent value="jobs" className="mt-0 flex-1 min-h-0 flex flex-col overflow-hidden">
|
||||
<div className="px-2 sm:px-4 pt-1 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap hidden sm:inline">Filter by repo:</span>
|
||||
<div className="px-2 sm:px-4">
|
||||
<ScheduleListToolbar search={searchQuery} onSearchChange={setSearchQuery} searchPlaceholder="Search jobs">
|
||||
<Combobox
|
||||
value={repoFilter}
|
||||
onChange={setRepoFilter}
|
||||
options={repoOptions}
|
||||
placeholder="All Repos"
|
||||
className="flex-1 sm:flex-none sm:min-w-[150px]"
|
||||
className="w-[130px] shrink-0 sm:w-[180px]"
|
||||
/>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="icon" aria-label="Filters" className="sm:hidden h-8 w-8 shrink-0 relative">
|
||||
<Button variant="outline" size="icon" aria-label="Filters" className="shrink-0 relative">
|
||||
<SlidersHorizontal className="h-3.5 w-3.5" />
|
||||
{(statusFilter !== 'all' || scheduleModeFilter !== 'all') && (
|
||||
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
||||
@@ -414,6 +473,7 @@ export function GlobalSchedules() {
|
||||
setScheduleModeFilter('all')
|
||||
setRepoFilter('all')
|
||||
setSortOption('nextRun')
|
||||
setSearchQuery('')
|
||||
}}
|
||||
className="text-xs text-muted-foreground"
|
||||
>
|
||||
@@ -484,57 +544,7 @@ export function GlobalSchedules() {
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<div className="hidden sm:flex flex-wrap gap-x-4 gap-y-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">Status:</span>
|
||||
<div className="flex gap-1">
|
||||
{statusOptions.map((opt) => (
|
||||
<Button
|
||||
key={opt.value}
|
||||
variant={statusFilter === opt.value ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setStatusFilter(opt.value as StatusFilter)}
|
||||
className="h-8 px-3 text-xs"
|
||||
>
|
||||
{opt.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">Mode:</span>
|
||||
<div className="flex gap-1">
|
||||
{modeOptions.map((opt) => (
|
||||
<Button
|
||||
key={opt.value}
|
||||
variant={scheduleModeFilter === opt.value ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setScheduleModeFilter(opt.value as ScheduleModeFilter)}
|
||||
className="h-8 px-3 text-xs"
|
||||
>
|
||||
{opt.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">Sort:</span>
|
||||
<div className="flex gap-1">
|
||||
{sortOptions.map((opt) => (
|
||||
<Button
|
||||
key={opt.value}
|
||||
variant={sortOption === opt.value ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setSortOption(opt.value as SortOption)}
|
||||
className="h-8 px-3 text-xs"
|
||||
>
|
||||
{opt.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ScheduleListToolbar>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-2 sm:px-4 pt-2 pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-4">
|
||||
@@ -568,7 +578,7 @@ export function GlobalSchedules() {
|
||||
<div className="space-y-2">
|
||||
<p className="text-lg font-semibold">No matching schedules</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Try adjusting your filters to see more results.
|
||||
Try a different search or adjust your filters.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
@@ -577,6 +587,7 @@ export function GlobalSchedules() {
|
||||
setStatusFilter('all')
|
||||
setScheduleModeFilter('all')
|
||||
setRepoFilter('all')
|
||||
setSearchQuery('')
|
||||
}}
|
||||
>
|
||||
Clear Filters
|
||||
@@ -585,134 +596,39 @@ export function GlobalSchedules() {
|
||||
</Card>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
|
||||
{filteredAndSortedJobs.map((job) => (
|
||||
<Card
|
||||
key={job.id}
|
||||
className="group cursor-pointer transition-all hover:shadow-md border-border/70 bg-card/60"
|
||||
onClick={() => navigate(`/repos/${job.repoId}/schedules`)}
|
||||
>
|
||||
<CardContent className="p-4 space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleNavigateToRepo(job.repoPath)
|
||||
}}
|
||||
className="text-xs text-muted-foreground hover:text-foreground hover:underline truncate block mb-1"
|
||||
>
|
||||
{job.repoName}
|
||||
</button>
|
||||
<h3 className="font-medium truncate">{job.name}</h3>
|
||||
<p className="mt-1 text-xs text-muted-foreground line-clamp-2">
|
||||
{job.description || 'No description'}
|
||||
</p>
|
||||
</div>
|
||||
<Badge className={getJobStatusTone(job)}>{job.enabled ? 'Enabled' : 'Paused'}</Badge>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-xs text-muted-foreground">
|
||||
<div className="flex items-center gap-2">
|
||||
<CalendarClock className="h-3.5 w-3.5" />
|
||||
<span className="truncate">
|
||||
{formatScheduleShortLabel(job)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock3 className="h-3.5 w-3.5" />
|
||||
<span>
|
||||
Next: {job.nextRunAt ? new Date(job.nextRunAt).toLocaleString() : 'Never'}
|
||||
</span>
|
||||
</div>
|
||||
{job.lastRunAt && (
|
||||
<div className="flex items-center gap-2">
|
||||
<History className="h-3.5 w-3.5" />
|
||||
<span>
|
||||
Last: {formatTimestamp(job.lastRunAt)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-2 border-t border-border/50">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 h-8 text-xs"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleRunNow(job)
|
||||
}}
|
||||
disabled={runMutation.isPending}
|
||||
>
|
||||
<PlayCircle className="h-3.5 w-3.5 mr-1" />
|
||||
Run
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
aria-label={job.enabled ? 'Pause schedule' : 'Enable schedule'}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleToggleEnabled(job)
|
||||
}}
|
||||
>
|
||||
{job.enabled ? (
|
||||
<Pause className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<Play className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
aria-label="Edit schedule"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleEdit(job)
|
||||
}}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
aria-label="Delete schedule"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
openDeleteJob(job.id)
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
<div className="overflow-x-auto rounded-lg border border-border/70">
|
||||
<ScheduleJobsTable
|
||||
jobs={filteredAndSortedJobs}
|
||||
showRepo
|
||||
onOpen={handleOpenJobRow}
|
||||
onOpenJob={handleOpenJobPage}
|
||||
onNavigateToRepo={handleNavigateToRepo}
|
||||
onRunNow={handleRunNow}
|
||||
onToggleEnabled={handleToggleEnabled}
|
||||
onEdit={handleEdit}
|
||||
onDelete={(job) => openDeleteJob(job.id)}
|
||||
onCancelRun={handleCancelJobRun}
|
||||
runPending={runMutation.isPending}
|
||||
cancelPending={cancelRunPending}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="runs" className="mt-0 flex-1 min-h-0 flex flex-col overflow-hidden">
|
||||
<div className="px-2 sm:px-4 pt-1 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap hidden sm:inline">Filter by repo:</span>
|
||||
<div className="px-2 sm:px-4">
|
||||
<ScheduleListToolbar search={runSearch} onSearchChange={setRunSearch} searchPlaceholder="Search runs">
|
||||
<Combobox
|
||||
value={runRepoFilter}
|
||||
onChange={setRunRepoFilter}
|
||||
options={runRepoOptions}
|
||||
placeholder="All Repos"
|
||||
className="flex-1 sm:flex-none sm:min-w-[150px]"
|
||||
className="w-[130px] shrink-0 sm:w-[180px]"
|
||||
/>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="icon" aria-label="Filters" className="sm:hidden h-8 w-8 shrink-0 relative">
|
||||
<Button variant="outline" size="icon" aria-label="Filters" className="shrink-0 relative">
|
||||
<SlidersHorizontal className="h-3.5 w-3.5" />
|
||||
{(runStatusFilter !== 'all' || runTriggerFilter !== 'all' || runSortOption !== 'startedAt') && (
|
||||
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
||||
@@ -726,6 +642,7 @@ export function GlobalSchedules() {
|
||||
setRunTriggerFilter('all')
|
||||
setRunRepoFilter('all')
|
||||
setRunSortOption('startedAt')
|
||||
setRunSearch('')
|
||||
}}
|
||||
className="text-xs text-muted-foreground"
|
||||
>
|
||||
@@ -796,163 +713,28 @@ export function GlobalSchedules() {
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<div className="hidden sm:flex flex-wrap gap-x-4 gap-y-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">Status:</span>
|
||||
<div className="flex gap-1">
|
||||
{runStatusOptions.map((opt) => (
|
||||
<Button
|
||||
key={opt.value}
|
||||
variant={runStatusFilter === opt.value ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setRunStatusFilter(opt.value)}
|
||||
className="h-8 px-3 text-xs"
|
||||
>
|
||||
{opt.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">Trigger:</span>
|
||||
<div className="flex gap-1">
|
||||
{runTriggerOptions.map((opt) => (
|
||||
<Button
|
||||
key={opt.value}
|
||||
variant={runTriggerFilter === opt.value ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setRunTriggerFilter(opt.value)}
|
||||
className="h-8 px-3 text-xs"
|
||||
>
|
||||
{opt.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">Sort:</span>
|
||||
<div className="flex gap-1">
|
||||
{runSortOptions.map((opt) => (
|
||||
<Button
|
||||
key={opt.value}
|
||||
variant={runSortOption === opt.value ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setRunSortOption(opt.value as 'startedAt' | 'jobName' | 'duration')}
|
||||
className="h-8 px-3 text-xs"
|
||||
>
|
||||
{opt.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{unreadTotal > 0 && (
|
||||
<Button variant="outline" size="sm" className="h-9 shrink-0" onClick={handleNextUnread}>
|
||||
Next unread ({unreadTotal})
|
||||
</Button>
|
||||
)}
|
||||
</ScheduleListToolbar>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-2 sm:px-4 pt-2 pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-4">
|
||||
{runsLoading && allRuns.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : selectedRunLookupLoading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : selectedRunLookupError ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Card className="max-w-md border-dashed border-border/70">
|
||||
<CardContent className="flex flex-col items-center gap-4 p-8 text-center">
|
||||
<div className="rounded-full border border-border bg-muted/40 p-4">
|
||||
<XCircle className="h-8 w-8 text-destructive" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-lg font-semibold">Failed to load run</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The selected run could not be loaded.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={() => { void refetchSelectedRun() }}>
|
||||
Retry
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => selectRun(null)}>
|
||||
Back to run history
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
) : selectedRunLookupNotFound ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Card className="max-w-md border-dashed border-border/70">
|
||||
<CardContent className="flex flex-col items-center gap-4 p-8 text-center">
|
||||
<div className="rounded-full border border-border bg-muted/40 p-4">
|
||||
<SearchX className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-lg font-semibold">Run not found</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The requested run no longer exists.
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => selectRun(null)}>
|
||||
Back to run history
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
) : sortedRuns.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Card className="max-w-md border-dashed border-border/70">
|
||||
<CardContent className="flex flex-col items-center gap-4 p-8 text-center">
|
||||
<div className="rounded-full border border-border bg-muted/40 p-4">
|
||||
<History className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-lg font-semibold">No runs found</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{runStatusFilter !== 'all' || runRepoFilter !== 'all' || runTriggerFilter !== 'all'
|
||||
? 'Try adjusting your filters to see more results.'
|
||||
: 'Schedule runs will appear here once jobs start executing.'}
|
||||
</p>
|
||||
</div>
|
||||
{(runStatusFilter !== 'all' || runRepoFilter !== 'all' || runTriggerFilter !== 'all' || runSortOption !== 'startedAt') && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setRunStatusFilter('all')
|
||||
setRunRepoFilter('all')
|
||||
setRunTriggerFilter('all')
|
||||
setRunSortOption('startedAt')
|
||||
}}
|
||||
>
|
||||
Clear Filters
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
) : (
|
||||
<RunHistoryCards
|
||||
<div className="overflow-x-auto rounded-lg border border-border/70">
|
||||
<ScheduleRunsTable
|
||||
runs={sortedRuns}
|
||||
runsLoading={runsLoading}
|
||||
runsLoading={runsLoading && allRuns.length === 0}
|
||||
selectedRunId={runId}
|
||||
onSelectRun={selectRun}
|
||||
onCancelRun={() => {
|
||||
if (runId) {
|
||||
const run = sortedRuns.find((r) => r.id === runId)
|
||||
if (run) {
|
||||
handleCancelRun(run.repoId, run.jobId, run.id)
|
||||
}
|
||||
}
|
||||
}}
|
||||
cancelRunPending={cancelRunPending}
|
||||
isFiltered={Boolean(debouncedRunSearch) || runStatusFilter !== 'all' || runRepoFilter !== 'all' || runTriggerFilter !== 'all'}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="prompts" className="mt-0 flex-1 min-h-0 flex flex-col overflow-hidden">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-4">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-2 sm:px-4 pt-2 pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-4">
|
||||
<PromptsTab
|
||||
promptDialog={promptDialog}
|
||||
templateId={templateId}
|
||||
@@ -966,6 +748,21 @@ export function GlobalSchedules() {
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<ScheduleRunDrawer
|
||||
run={selectedRun}
|
||||
open={runId !== null}
|
||||
onClose={() => selectRun(null)}
|
||||
onCancelRun={handleCancelSelectedRun}
|
||||
cancelPending={cancelRunPending}
|
||||
runLoading={selectedRunLookupLoading}
|
||||
runError={selectedRunLookupError}
|
||||
onRetry={() => { void refetchSelectedRun() }}
|
||||
onNextUnread={handleNextUnread}
|
||||
nextUnreadCount={unreadTotal}
|
||||
onPrev={selectedRunPrev}
|
||||
onNext={selectedRunNext}
|
||||
/>
|
||||
|
||||
<ScheduleJobDialog
|
||||
open={dialog === 'new' || dialog === 'edit'}
|
||||
onOpenChange={(open) => {
|
||||
|
||||
@@ -2,15 +2,14 @@ import { useEffect, useMemo, useState } from 'react'
|
||||
import { useLocation, useParams } from 'react-router-dom'
|
||||
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
|
||||
import {
|
||||
useAllSchedules,
|
||||
useCancelRepoScheduleRun,
|
||||
useClearRepoScheduleRuns,
|
||||
useCreateRepoSchedule,
|
||||
useDeleteRepoSchedule,
|
||||
useDeleteRepoScheduleRun,
|
||||
useRepoSchedule,
|
||||
useRepoScheduleRun,
|
||||
useRepoScheduleRuns,
|
||||
useRepoSchedules,
|
||||
useRunRepoSchedule,
|
||||
useUpdateRepoSchedule,
|
||||
} from '@/hooks/useSchedules'
|
||||
@@ -18,8 +17,9 @@ import { useRepoActivity } from '@/hooks/useRepoActivity'
|
||||
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
|
||||
import { useScheduleUrlState } from '@/hooks/useScheduleUrlState'
|
||||
import { useSidebarAction } from '@/hooks/useSidebarAction'
|
||||
import { ScheduleJobDialog, JobsTab, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
|
||||
import { toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
|
||||
import { ScheduleJobDialog, ScheduleJobsTable, ScheduleListToolbar, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
|
||||
import { matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
|
||||
import type { ScheduleJobWithRepo } from '@/api/schedules'
|
||||
import { Header } from '@/components/ui/header'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
@@ -54,10 +54,13 @@ export function Schedules() {
|
||||
|
||||
useRepoActivity(repoId ?? 0, Boolean(scheduleTarget) && scheduleTarget?.kind === 'repo')
|
||||
|
||||
const { data: jobs, isLoading: jobsLoading } = useRepoSchedules(repoId)
|
||||
const { data: allSchedules, isLoading: jobsLoading } = useAllSchedules()
|
||||
const jobs = useMemo(
|
||||
() => allSchedules?.filter((job) => job.repoId === repoId),
|
||||
[allSchedules, repoId],
|
||||
)
|
||||
const { data: selectedJob, isFetching: isJobFetching } = useRepoSchedule(repoId, jobId)
|
||||
const { data: runs, isLoading: runsLoading } = useRepoScheduleRuns(repoId, jobId, 30)
|
||||
const { data: selectedRunDetails, isLoading: selectedRunLoading } = useRepoScheduleRun(repoId, jobId, runId)
|
||||
|
||||
const createMutation = useCreateRepoSchedule()
|
||||
const updateMutation = useUpdateRepoSchedule()
|
||||
@@ -67,6 +70,7 @@ export function Schedules() {
|
||||
const clearRunsMutation = useClearRepoScheduleRuns()
|
||||
const deleteRunMutation = useDeleteRepoScheduleRun()
|
||||
|
||||
const [jobSearch, setJobSearch] = useState('')
|
||||
const [clearRunsOpen, setClearRunsOpen] = useState(false)
|
||||
const [runToDelete, setRunToDelete] = useState<number | null>(null)
|
||||
|
||||
@@ -117,21 +121,10 @@ export function Schedules() {
|
||||
|
||||
useEffect(() => {
|
||||
if (runs === undefined) return
|
||||
|
||||
if (!runs.length) {
|
||||
if (runId !== null) selectRun(null)
|
||||
return
|
||||
}
|
||||
|
||||
const stillExists = runId !== null && runs.some((run) => run.id === runId)
|
||||
if (!stillExists) {
|
||||
const newRunId = runs[0]?.id ?? null
|
||||
if (newRunId !== runId) selectRun(newRunId)
|
||||
}
|
||||
if (runId === null) return
|
||||
if (!runs.some((run) => run.id === runId)) selectRun(null)
|
||||
}, [runs, runId, selectRun])
|
||||
|
||||
const activeRunSummary = useMemo(() => runs?.find((run) => run.id === runId) ?? null, [runs, runId])
|
||||
const activeRun = selectedRunDetails ?? activeRunSummary
|
||||
const runningRun = useMemo(() => runs?.find((run) => run.status === 'running') ?? null, [runs])
|
||||
|
||||
if (scheduleTargetLoading || jobsLoading) {
|
||||
@@ -191,24 +184,16 @@ export function Schedules() {
|
||||
})
|
||||
}
|
||||
|
||||
const handleToggleEnabled = () => {
|
||||
if (!selectedJob) {
|
||||
return
|
||||
}
|
||||
|
||||
const handleToggleEnabled = (job: ScheduleJob) => {
|
||||
updateMutation.mutate({
|
||||
repoId: repoId!,
|
||||
jobId: selectedJob.id,
|
||||
data: { enabled: !selectedJob.enabled },
|
||||
jobId: job.id,
|
||||
data: { enabled: !job.enabled },
|
||||
})
|
||||
}
|
||||
|
||||
const handleRunNow = () => {
|
||||
if (!selectedJob) {
|
||||
return
|
||||
}
|
||||
|
||||
runMutation.mutate({ repoId: repoId!, jobId: selectedJob.id }, {
|
||||
const handleRunNow = (job: ScheduleJob) => {
|
||||
runMutation.mutate({ repoId: repoId!, jobId: job.id }, {
|
||||
onSuccess: (run) => {
|
||||
selectRun(run.id)
|
||||
},
|
||||
@@ -216,14 +201,15 @@ export function Schedules() {
|
||||
}
|
||||
|
||||
const handleCancelRun = () => {
|
||||
if (!activeRun || activeRun.status !== 'running') {
|
||||
const target = runId !== null ? runs?.find((run) => run.id === runId) ?? null : null
|
||||
if (!target || target.status !== 'running') {
|
||||
return
|
||||
}
|
||||
|
||||
cancelRunMutation.mutate({
|
||||
repoId: repoId!,
|
||||
jobId: activeRun.jobId,
|
||||
runId: activeRun.id,
|
||||
jobId: target.jobId,
|
||||
runId: target.id,
|
||||
}, {
|
||||
onSuccess: (run) => {
|
||||
selectRun(run.id)
|
||||
@@ -231,6 +217,18 @@ export function Schedules() {
|
||||
})
|
||||
}
|
||||
|
||||
const handleCancelJobRun = (job: ScheduleJobWithRepo) => {
|
||||
if (!job.lastRun) {
|
||||
return
|
||||
}
|
||||
|
||||
cancelRunMutation.mutate({
|
||||
repoId: repoId!,
|
||||
jobId: job.id,
|
||||
runId: job.lastRun.id,
|
||||
})
|
||||
}
|
||||
|
||||
const handleClearHistory = () => {
|
||||
if (jobId === null) {
|
||||
return
|
||||
@@ -298,19 +296,34 @@ export function Schedules() {
|
||||
) : (
|
||||
<>
|
||||
{repoScheduleTab === 'jobs' && (
|
||||
<JobsTab
|
||||
jobs={jobs ?? []}
|
||||
selectedJobId={jobId}
|
||||
onSelectJob={handleSelectJob}
|
||||
/>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<ScheduleListToolbar search={jobSearch} onSearchChange={setJobSearch} searchPlaceholder="Search jobs" />
|
||||
<div className="min-h-0 flex-1 overflow-y-auto pt-2 pb-2">
|
||||
<div className="overflow-x-auto rounded-lg border border-border/70">
|
||||
<ScheduleJobsTable
|
||||
jobs={(jobs ?? []).filter((job) => matchesScheduleJobSearch(job, jobSearch))}
|
||||
showRepo={false}
|
||||
selectedJobId={jobId}
|
||||
onOpen={(job) => handleSelectJob(job.id)}
|
||||
onRunNow={handleRunNow}
|
||||
onToggleEnabled={handleToggleEnabled}
|
||||
onEdit={(job) => openEditJob(job.id)}
|
||||
onDelete={(job) => openDeleteJob(job.id)}
|
||||
onCancelRun={handleCancelJobRun}
|
||||
runPending={runMutation.isPending}
|
||||
cancelPending={cancelRunMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{repoScheduleTab === 'detail' && (
|
||||
<JobDetailTab
|
||||
selectedJob={selectedJob}
|
||||
onEdit={(job) => openEditJob(job.id)}
|
||||
onDelete={openDeleteJob}
|
||||
onToggleEnabled={handleToggleEnabled}
|
||||
onRunNow={handleRunNow}
|
||||
onToggleEnabled={() => { if (selectedJob) handleToggleEnabled(selectedJob) }}
|
||||
onRunNow={() => { if (selectedJob) handleRunNow(selectedJob) }}
|
||||
updatePending={updateMutation.isPending}
|
||||
runPending={runMutation.isPending}
|
||||
runningRun={Boolean(runningRun)}
|
||||
@@ -319,13 +332,11 @@ export function Schedules() {
|
||||
)}
|
||||
{repoScheduleTab === 'runs' && (
|
||||
<RunHistoryTab
|
||||
repoId={repoId}
|
||||
selectedJob={selectedJob}
|
||||
runs={runs}
|
||||
runsLoading={runsLoading}
|
||||
runId={runId}
|
||||
onSelectRun={selectRun}
|
||||
activeRun={activeRun}
|
||||
selectedRunLoading={selectedRunLoading}
|
||||
onCancelRun={handleCancelRun}
|
||||
cancelRunPending={cancelRunMutation.isPending}
|
||||
onClearHistory={() => setClearRunsOpen(true)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { GlobalSchedules } from '../GlobalSchedules'
|
||||
@@ -12,8 +12,11 @@ const mocks = vi.hoisted(() => ({
|
||||
useDeleteRepoSchedule: vi.fn(),
|
||||
useRunRepoSchedule: vi.fn(),
|
||||
useCancelRepoScheduleRun: vi.fn(),
|
||||
useUnreadScheduleRuns: vi.fn(),
|
||||
useScheduleUrlState: vi.fn(),
|
||||
RunHistoryCards: vi.fn(() => null),
|
||||
ScheduleJobsTable: vi.fn(() => null),
|
||||
ScheduleRunsTable: vi.fn(() => null),
|
||||
ScheduleRunDrawer: vi.fn(() => null),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
@@ -24,15 +27,23 @@ vi.mock('@/hooks/useSchedules', () => ({
|
||||
useDeleteRepoSchedule: mocks.useDeleteRepoSchedule,
|
||||
useRunRepoSchedule: mocks.useRunRepoSchedule,
|
||||
useCancelRepoScheduleRun: mocks.useCancelRepoScheduleRun,
|
||||
useUnreadScheduleRuns: mocks.useUnreadScheduleRuns,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useScheduleUrlState', () => ({
|
||||
useScheduleUrlState: mocks.useScheduleUrlState,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/notifications/ScheduleReportsBell', () => ({
|
||||
ScheduleReportsBell: vi.fn(() => null),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/schedules', () => ({
|
||||
ScheduleJobDialog: vi.fn(() => null),
|
||||
RunHistoryCards: mocks.RunHistoryCards,
|
||||
ScheduleJobsTable: mocks.ScheduleJobsTable,
|
||||
ScheduleRunsTable: mocks.ScheduleRunsTable,
|
||||
ScheduleRunDrawer: mocks.ScheduleRunDrawer,
|
||||
ScheduleListToolbar: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
|
||||
PromptsTab: vi.fn(() => null),
|
||||
}))
|
||||
|
||||
@@ -45,6 +56,7 @@ function makeRun(overrides: Record<string, unknown> = {}) {
|
||||
status: 'completed',
|
||||
startedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
finishedAt: Date.UTC(2026, 2, 9, 12, 5, 0),
|
||||
viewedAt: 123,
|
||||
createdAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
sessionId: 'ses-1',
|
||||
sessionTitle: 'Run title',
|
||||
@@ -61,6 +73,36 @@ function makeRun(overrides: Record<string, unknown> = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
function makeJob(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 7,
|
||||
repoId: 42,
|
||||
name: 'Weekly summary',
|
||||
description: 'Summarize the week',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Summarize the week',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
lastRunAt: null,
|
||||
nextRunAt: null,
|
||||
repoName: 'my-repo',
|
||||
repoPath: '/home/user/my-repo',
|
||||
repoUrl: 'https://example.com/my-repo',
|
||||
lastRun: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function createMockScheduleUrlState(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
scheduleTab: 'runs',
|
||||
@@ -110,11 +152,24 @@ const renderGlobalSchedules = () => {
|
||||
)
|
||||
}
|
||||
|
||||
const runHistoryProps = () => mocks.RunHistoryCards.mock.calls.at(-1)?.[0] as {
|
||||
const runsTableProps = () => mocks.ScheduleRunsTable.mock.calls.at(-1)?.[0] as {
|
||||
runs: Array<{ id: number }>
|
||||
selectedRunId: number | null
|
||||
}
|
||||
|
||||
const drawerProps = () => mocks.ScheduleRunDrawer.mock.calls.at(-1)?.[0] as {
|
||||
run: { id: number } | null
|
||||
open: boolean
|
||||
runLoading: boolean
|
||||
runError: boolean
|
||||
onRetry?: () => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const jobsTableProps = () => mocks.ScheduleJobsTable.mock.calls.at(-1)?.[0] as {
|
||||
onOpen: (job: unknown) => void
|
||||
}
|
||||
|
||||
describe('GlobalSchedules run history', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
@@ -130,6 +185,7 @@ describe('GlobalSchedules run history', () => {
|
||||
mocks.useDeleteRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
mocks.useRunRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
mocks.useCancelRepoScheduleRun.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 0, failed: 0 } })
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState())
|
||||
})
|
||||
|
||||
@@ -142,10 +198,10 @@ describe('GlobalSchedules run history', () => {
|
||||
renderGlobalSchedules()
|
||||
|
||||
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 999 }, true)
|
||||
const props = runHistoryProps()
|
||||
const props = runsTableProps()
|
||||
expect(props.selectedRunId).toBe(999)
|
||||
expect(props.runs.some((run) => run.id === 999)).toBe(true)
|
||||
expect(screen.queryByText('No runs found')).not.toBeInTheDocument()
|
||||
expect(drawerProps().run?.id).toBe(999)
|
||||
})
|
||||
|
||||
it('does not duplicate a selected run already present in history', () => {
|
||||
@@ -155,54 +211,44 @@ describe('GlobalSchedules run history', () => {
|
||||
renderGlobalSchedules()
|
||||
|
||||
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 5 }, false)
|
||||
const props = runHistoryProps()
|
||||
const props = runsTableProps()
|
||||
expect(props.runs.filter((run) => run.id === 5)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('shows loading instead of no runs while the selected run lookup is pending', () => {
|
||||
it('reports loading through the drawer while the selected run lookup is pending', () => {
|
||||
selectedRunResult = { data: undefined, isLoading: true, isError: false }
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999 }))
|
||||
|
||||
const { container } = renderGlobalSchedules()
|
||||
renderGlobalSchedules()
|
||||
|
||||
expect(screen.queryByText('No runs found')).not.toBeInTheDocument()
|
||||
expect(container.querySelector('.animate-spin')).not.toBeNull()
|
||||
expect(mocks.RunHistoryCards).not.toHaveBeenCalled()
|
||||
expect(drawerProps().runLoading).toBe(true)
|
||||
expect(drawerProps().run).toBeNull()
|
||||
expect(mocks.ScheduleRunsTable).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows run not found when the selected run lookup returns empty', () => {
|
||||
it('reports not found through the drawer when the selected run lookup returns empty', () => {
|
||||
selectedRunResult = { data: [], isLoading: false, isError: false }
|
||||
const selectRun = vi.fn()
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999, selectRun }))
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999 }))
|
||||
|
||||
renderGlobalSchedules()
|
||||
|
||||
expect(screen.getByText('Run not found')).toBeInTheDocument()
|
||||
expect(screen.queryByText('No runs found')).not.toBeInTheDocument()
|
||||
expect(mocks.RunHistoryCards).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Back to run history' }))
|
||||
|
||||
expect(selectRun).toHaveBeenCalledWith(null)
|
||||
expect(drawerProps().run).toBeNull()
|
||||
expect(drawerProps().runLoading).toBe(false)
|
||||
expect(drawerProps().runError).toBe(false)
|
||||
expect(mocks.ScheduleRunsTable).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows an error with retry and back actions when the selected run lookup fails', () => {
|
||||
it('reports an error with a retry through the drawer when the lookup fails', () => {
|
||||
const refetch = vi.fn()
|
||||
selectedRunResult = { data: undefined, isLoading: false, isError: true, refetch }
|
||||
const selectRun = vi.fn()
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999, selectRun }))
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999 }))
|
||||
|
||||
renderGlobalSchedules()
|
||||
|
||||
expect(screen.getByText('Failed to load run')).toBeInTheDocument()
|
||||
expect(screen.queryByText('No runs found')).not.toBeInTheDocument()
|
||||
expect(mocks.RunHistoryCards).not.toHaveBeenCalled()
|
||||
expect(drawerProps().runError).toBe(true)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
drawerProps().onRetry?.()
|
||||
expect(refetch).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Back to run history' }))
|
||||
expect(selectRun).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('renders the cached selected run when a background refetch fails', () => {
|
||||
@@ -211,10 +257,9 @@ describe('GlobalSchedules run history', () => {
|
||||
|
||||
renderGlobalSchedules()
|
||||
|
||||
expect(screen.queryByText('Failed to load run')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Run not found')).not.toBeInTheDocument()
|
||||
expect(mocks.RunHistoryCards).toHaveBeenCalled()
|
||||
const props = runHistoryProps()
|
||||
expect(drawerProps().runError).toBe(false)
|
||||
expect(drawerProps().run?.id).toBe(999)
|
||||
const props = runsTableProps()
|
||||
expect(props.selectedRunId).toBe(999)
|
||||
expect(props.runs.filter((run) => run.id === 999)).toHaveLength(1)
|
||||
})
|
||||
@@ -238,7 +283,7 @@ describe('GlobalSchedules run history', () => {
|
||||
)
|
||||
|
||||
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 1000 }, true)
|
||||
expect(runHistoryProps().runs.some((run) => run.id === 1000)).toBe(true)
|
||||
expect(runsTableProps().runs.some((run) => run.id === 1000)).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores cached selected run data when the selection is cleared', () => {
|
||||
@@ -248,9 +293,9 @@ describe('GlobalSchedules run history', () => {
|
||||
|
||||
const { rerender } = renderGlobalSchedules()
|
||||
|
||||
expect(runHistoryProps().runs.some((run) => run.id === 999)).toBe(true)
|
||||
expect(runsTableProps().runs.some((run) => run.id === 999)).toBe(true)
|
||||
|
||||
mocks.RunHistoryCards.mockClear()
|
||||
mocks.ScheduleRunsTable.mockClear()
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: null }))
|
||||
|
||||
rerender(
|
||||
@@ -259,15 +304,39 @@ describe('GlobalSchedules run history', () => {
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
expect(screen.getByText('No runs found')).toBeInTheDocument()
|
||||
expect(mocks.RunHistoryCards).not.toHaveBeenCalled()
|
||||
expect(drawerProps().open).toBe(false)
|
||||
expect(runsTableProps().runs.some((run) => run.id === 999)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not query the selected run when the runs tab is inactive', () => {
|
||||
it('queries the selected run on the jobs tab as well', () => {
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'jobs', runId: 999 }))
|
||||
|
||||
renderGlobalSchedules()
|
||||
|
||||
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 999 }, false)
|
||||
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 999 }, true)
|
||||
})
|
||||
|
||||
it('opens the report drawer from a job row that has a last run', () => {
|
||||
const selectRun = vi.fn()
|
||||
mocks.useAllSchedules.mockReturnValue({
|
||||
data: [makeJob({ lastRun: { id: 5, status: 'completed', startedAt: 0, finishedAt: 1, viewedAt: 1, preview: null } })],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
})
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'jobs', runId: null, selectRun }))
|
||||
|
||||
renderGlobalSchedules()
|
||||
|
||||
jobsTableProps().onOpen(makeJob({ lastRun: { id: 5 } }))
|
||||
|
||||
expect(selectRun).toHaveBeenCalledWith(5)
|
||||
})
|
||||
|
||||
it('keeps the jobs tab visible with the empty state when there are no jobs', () => {
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'jobs', runId: null }))
|
||||
|
||||
renderGlobalSchedules()
|
||||
|
||||
expect(screen.getByText('No schedules yet')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -6,10 +6,9 @@ import { Schedules } from '../Schedules'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useScheduleTarget: vi.fn(),
|
||||
useRepoSchedules: vi.fn(),
|
||||
useAllSchedules: vi.fn(),
|
||||
useRepoSchedule: vi.fn(),
|
||||
useRepoScheduleRuns: vi.fn(),
|
||||
useRepoScheduleRun: vi.fn(),
|
||||
useCreateRepoSchedule: vi.fn(),
|
||||
useUpdateRepoSchedule: vi.fn(),
|
||||
useDeleteRepoSchedule: vi.fn(),
|
||||
@@ -32,10 +31,9 @@ vi.mock('@/hooks/useScheduleTarget', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useRepoSchedules: mocks.useRepoSchedules,
|
||||
useAllSchedules: mocks.useAllSchedules,
|
||||
useRepoSchedule: mocks.useRepoSchedule,
|
||||
useRepoScheduleRuns: mocks.useRepoScheduleRuns,
|
||||
useRepoScheduleRun: mocks.useRepoScheduleRun,
|
||||
useCreateRepoSchedule: mocks.useCreateRepoSchedule,
|
||||
useUpdateRepoSchedule: mocks.useUpdateRepoSchedule,
|
||||
useDeleteRepoSchedule: mocks.useDeleteRepoSchedule,
|
||||
@@ -54,15 +52,17 @@ vi.mock('@/hooks/useScheduleUrlState', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('@/components/schedules', () => ({
|
||||
ScheduleListToolbar: () => null,
|
||||
ScheduleJobDialog: vi.fn(({ onOpenChange }) => (
|
||||
<div>
|
||||
ScheduleJobDialog
|
||||
<button onClick={() => onOpenChange(false)} data-testid="close-job-dialog">Close</button>
|
||||
</div>
|
||||
)),
|
||||
JobsTab: vi.fn(({ onSelectJob }) => (
|
||||
ScheduleJobsTable: vi.fn(({ onOpen }) => (
|
||||
<div>
|
||||
<button onClick={() => onSelectJob(123)} data-testid="select-job">Select Job</button>
|
||||
ScheduleJobsTable
|
||||
<button onClick={() => onOpen({ id: 123, repoId: 5 })} data-testid="select-job">Select Job</button>
|
||||
</div>
|
||||
)),
|
||||
JobDetailTab: vi.fn(({ onEdit, onDelete, onRunNow }) => (
|
||||
@@ -151,10 +151,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useAllSchedules.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('0')
|
||||
|
||||
@@ -175,10 +174,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useAllSchedules.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('0')
|
||||
|
||||
@@ -200,10 +198,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useAllSchedules.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('0')
|
||||
|
||||
@@ -248,10 +245,9 @@ describe('Schedules', () => {
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({
|
||||
scheduleTab: 'detail',
|
||||
}))
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useAllSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
|
||||
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
|
||||
mocks.useRunRepoSchedule.mockReturnValue({ mutate: mutateMock, isPending: false })
|
||||
|
||||
renderSchedules('0')
|
||||
@@ -277,10 +273,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useAllSchedules.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')
|
||||
|
||||
@@ -303,10 +298,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useAllSchedules.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')
|
||||
|
||||
@@ -331,10 +325,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useAllSchedules.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')
|
||||
|
||||
@@ -380,10 +373,9 @@ describe('Schedules', () => {
|
||||
nextRunAt: null,
|
||||
skillMetadata: null,
|
||||
}
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useAllSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
|
||||
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
|
||||
|
||||
renderSchedules('5')
|
||||
|
||||
@@ -401,10 +393,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: true,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: undefined, isLoading: false })
|
||||
mocks.useAllSchedules.mockReturnValue({ data: undefined, isLoading: false })
|
||||
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
|
||||
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
|
||||
|
||||
renderSchedules('999')
|
||||
|
||||
@@ -417,10 +408,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: true,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: undefined, isLoading: false })
|
||||
mocks.useAllSchedules.mockReturnValue({ data: undefined, isLoading: false })
|
||||
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
|
||||
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
|
||||
|
||||
renderSchedules('0')
|
||||
|
||||
@@ -466,10 +456,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useAllSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
|
||||
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
|
||||
|
||||
renderSchedules('5')
|
||||
|
||||
@@ -517,10 +506,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useAllSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
|
||||
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
|
||||
mocks.useDeleteRepoSchedule.mockReturnValue({ mutate: deleteMutate, isPending: false })
|
||||
|
||||
renderSchedules('5')
|
||||
@@ -571,10 +559,9 @@ describe('Schedules', () => {
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
})
|
||||
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useAllSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
|
||||
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
|
||||
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
|
||||
|
||||
renderSchedules('5')
|
||||
|
||||
|
||||
Reference in new issue
Block a user