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,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}
|
||||
|
||||
Reference in new issue
Block a user