diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts index 989c8fe0..5ff232a4 100644 --- a/backend/src/db/schedules.ts +++ b/backend/src/db/schedules.ts @@ -373,3 +373,40 @@ export function listScheduleRunsByJob(db: Database, repoId: number, jobId: numbe const rows = stmt.all(repoId, jobId, limit) as ScheduleRunRow[] return rows.map(rowToScheduleRun) } + +export interface ScheduleJobWithRepo extends ScheduleJob { + repoName: string + repoPath: string + repoUrl: string +} + +interface ScheduleJobWithRepoRow extends ScheduleJobRow { + repo_url: string + repo_path: string +} + +function repoNameFromPath(repoPath: string): string { + if (!repoPath || repoPath === '/') return 'Unknown' + return repoPath.split(/[\\/]/).pop() ?? repoPath +} + +function rowToScheduleJobWithRepo(row: ScheduleJobWithRepoRow): ScheduleJobWithRepo { + const job = rowToScheduleJob(row) + return { + ...job, + repoName: repoNameFromPath(row.repo_path), + repoPath: row.repo_path, + repoUrl: row.repo_url, + } +} + +export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[] { + const stmt = db.prepare(` + SELECT sj.*, r.repo_url, r.local_path as repo_path + FROM schedule_jobs sj + JOIN repos r ON sj.repo_id = r.id + ORDER BY r.local_path, sj.name + `) + const rows = stmt.all() as ScheduleJobWithRepoRow[] + return rows.map(rowToScheduleJobWithRepo) +} diff --git a/backend/src/index.ts b/backend/src/index.ts index 729bd736..8cdd399d 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -15,6 +15,7 @@ import { createHealthRoutes } from './routes/health' import { createTTSRoutes, cleanupExpiredCache } from './routes/tts'; import { createSTTRoutes } from './routes/stt' import { createFileRoutes } from './routes/files' +import { createScheduleRoutes } from './routes/schedules' async function getAppVersion(): Promise { try { @@ -370,6 +371,7 @@ protectedApi.route('/ssh', createSSHRoutes(gitAuthService)) protectedApi.route('/notifications', createNotificationRoutes(notificationService)) protectedApi.route('/memory', createMemoryRoutes(db)) protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db)) +protectedApi.route('/schedules', createScheduleRoutes(scheduleService)) app.route('/api', protectedApi) diff --git a/backend/src/routes/schedules.ts b/backend/src/routes/schedules.ts index a2bf402c..8d44d822 100644 --- a/backend/src/routes/schedules.ts +++ b/backend/src/routes/schedules.ts @@ -35,6 +35,15 @@ function parseRunListLimit(value: string | undefined): number { export function createScheduleRoutes(scheduleService: ScheduleService) { const app = new Hono() + app.get('/all', (c) => { + try { + const jobs = scheduleService.listAllJobsWithRepos() + return c.json({ jobs }) + } catch (error) { + return handleScheduleError(c, error, 'Failed to list all schedules') + } + }) + app.get('/', (c) => { try { const repoId = parseId(c.req.param('id'), 'repo id') diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 85dcd2ff..2a4806b6 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -8,6 +8,7 @@ import { type UpdateScheduleJobRequest, } from '@opencode-manager/shared/types' import { getRepoById } from '../db/queries' +import type { ScheduleJobWithRepo } from '../db/schedules' import { createScheduleJob, createScheduleRun, @@ -15,6 +16,7 @@ import { getScheduleJobById, getRunningScheduleRunByJob, getScheduleRunById, + listAllScheduleJobsWithRepos, listEnabledScheduleJobs, listScheduleJobsByRepo, listRunningScheduleRuns, @@ -359,6 +361,10 @@ export class ScheduleService { return listEnabledScheduleJobs(this.db) } + listAllJobsWithRepos(): ScheduleJobWithRepo[] { + return listAllScheduleJobsWithRepos(this.db) + } + async recoverRunningRuns(): Promise { const runningRuns = listRunningScheduleRuns(this.db) diff --git a/backend/test/routes/schedules.test.ts b/backend/test/routes/schedules.test.ts index 455767a8..267357d1 100644 --- a/backend/test/routes/schedules.test.ts +++ b/backend/test/routes/schedules.test.ts @@ -231,4 +231,23 @@ describe('Schedule Routes', () => { timezone: 'America/New_York', })) }) + + it('lists all schedules across all repos', async () => { + mocks.scheduleService.listAllJobsWithRepos.mockReturnValue([ + { id: 1, name: 'Job 1', repoName: 'Repo A', repoPath: '/path/a', repoUrl: 'https://repo-a' }, + { id: 2, name: 'Job 2', repoName: 'Repo B', repoPath: '/path/b', repoUrl: 'https://repo-b' }, + ]) + + const response = await app.request('/repos/42/schedules/all') + const body = await response.json() as { jobs: Array<{ id: number; name: string; repoName: string }> } + + expect(response.status).toBe(200) + expect(body.jobs).toHaveLength(2) + expect(body.jobs[0]).toEqual(expect.objectContaining({ + id: 1, + name: 'Job 1', + repoName: 'Repo A', + })) + expect(mocks.scheduleService.listAllJobsWithRepos).toHaveBeenCalled() + }) }) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d9c6322c..804e35cf 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -8,6 +8,7 @@ import { RepoDetail } from './pages/RepoDetail' import { SessionDetail } from './pages/SessionDetail' import { Memories } from './pages/Memories' import { Schedules } from './pages/Schedules' +import { GlobalSchedules } from './pages/GlobalSchedules' import { Login } from './pages/Login' import { Register } from './pages/Register' import { Setup } from './pages/Setup' @@ -142,6 +143,11 @@ const router = createBrowserRouter([ element: , loader: protectedLoader, }, + { + path: '/schedules', + element: , + loader: protectedLoader, + }, ], }, ]) diff --git a/frontend/src/api/schedules.ts b/frontend/src/api/schedules.ts index cf5553af..586905dd 100644 --- a/frontend/src/api/schedules.ts +++ b/frontend/src/api/schedules.ts @@ -7,10 +7,45 @@ import type { UpdateScheduleJobRequest, } from '@opencode-manager/shared/types' +export interface ScheduleJobWithRepo extends ScheduleJob { + repoName: string + repoPath: string + repoUrl: string +} + +export interface ScheduleCount { + total: number + enabled: number +} + +export async function listAllSchedules(): Promise<{ jobs: ScheduleJobWithRepo[] }> { + return fetchWrapper(`${API_BASE_URL}/api/schedules/all`) +} + export async function listRepoSchedules(repoId: number): Promise<{ jobs: ScheduleJob[] }> { return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules`) } +export async function getScheduleCounts(): Promise> { + const response = await fetchWrapper(`${API_BASE_URL}/api/schedules/all`) + const jobs = response.jobs as ScheduleJobWithRepo[] + const counts = new Map() + + jobs.forEach((job) => { + const existing = counts.get(job.repoId) + if (existing) { + existing.total += 1 + if (job.enabled) { + existing.enabled += 1 + } + } else { + counts.set(job.repoId, { total: 1, enabled: job.enabled ? 1 : 0 }) + } + }) + + return counts +} + export async function getRepoSchedule(repoId: number, jobId: number): Promise<{ job: ScheduleJob }> { return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`) } diff --git a/frontend/src/hooks/useSchedules.ts b/frontend/src/hooks/useSchedules.ts index 6ec349c5..6c7feeb2 100644 --- a/frontend/src/hooks/useSchedules.ts +++ b/frontend/src/hooks/useSchedules.ts @@ -6,12 +6,24 @@ import { deleteRepoSchedule, getRepoSchedule, getRepoScheduleRun, + listAllSchedules, listRepoScheduleRuns, listRepoSchedules, runRepoSchedule, updateRepoSchedule, } from '@/api/schedules' import { showToast } from '@/lib/toast' +import type { ScheduleJobWithRepo } from '@/api/schedules' + +export function useAllSchedules() { + return useQuery({ + queryKey: ['all-schedules'], + queryFn: async () => { + const response = await listAllSchedules() + return response.jobs as ScheduleJobWithRepo[] + }, + }) +} export function useRepoSchedules(repoId: number | undefined) { return useQuery({ diff --git a/frontend/src/pages/GlobalSchedules.tsx b/frontend/src/pages/GlobalSchedules.tsx new file mode 100644 index 00000000..78ab034b --- /dev/null +++ b/frontend/src/pages/GlobalSchedules.tsx @@ -0,0 +1,575 @@ +import { useState, useMemo } from 'react' +import { useNavigate } from 'react-router-dom' +import { useAllSchedules } from '@/hooks/useSchedules' +import { useDeleteRepoSchedule, useRunRepoSchedule, useUpdateRepoSchedule } from '@/hooks/useSchedules' +import { ScheduleJobDialog } from '@/components/schedules' +import type { CreateScheduleJobRequest } from '@opencode-manager/shared/types' +import { toUpdateScheduleRequest, formatScheduleShortLabel, getJobStatusTone, formatTimestamp } from '@/components/schedules/schedule-utils' +import { Header } from '@/components/ui/header' +import { Button } from '@/components/ui/button' +import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuCheckboxItem, DropdownMenuItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator } from '@/components/ui/dropdown-menu' +import { Badge } from '@/components/ui/badge' +import { Card, CardContent } from '@/components/ui/card' +import { DeleteDialog } from '@/components/ui/delete-dialog' +import { CalendarClock, Loader2, Plus, ArrowLeft, Play, Pencil, Trash2, Pause, PlayCircle, Clock3, History, SlidersHorizontal } from 'lucide-react' + +import type { ScheduleJobWithRepo } from '@/api/schedules' +import { Combobox } from '@/components/ui/combobox' + +type StatusFilter = 'all' | 'enabled' | 'disabled' +type ScheduleModeFilter = 'all' | 'cron' | 'interval' +type SortOption = 'nextRun' | 'name' | 'repo' + +export function GlobalSchedules() { + const navigate = useNavigate() + const [dialogOpen, setDialogOpen] = useState(false) + const [editingJob, setEditingJob] = useState(null) + const [deleteJobId, setDeleteJobId] = useState(null) + const [statusFilter, setStatusFilter] = useState('all') + const [scheduleModeFilter, setScheduleModeFilter] = useState('all') + const [repoFilter, setRepoFilter] = useState('all') + const [sortOption, setSortOption] = useState('nextRun') + + const { data: jobs = [], isLoading, error } = useAllSchedules() + + const deleteMutation = useDeleteRepoSchedule(undefined) + const runMutation = useRunRepoSchedule(undefined) + const updateMutation = useUpdateRepoSchedule(undefined) + + const uniqueRepos = useMemo(() => { + const repoMap = new Map() + jobs.forEach((job) => { + repoMap.set(job.repoPath, { name: job.repoName, url: job.repoUrl }) + }) + return Array.from(repoMap.entries()).map(([path, info]) => ({ + path, + name: info.name, + url: info.url, + })) + }, [jobs]) + + const filteredAndSortedJobs = useMemo(() => { + let filtered = [...jobs] + + if (statusFilter !== 'all') { + filtered = filtered.filter((job) => + statusFilter === 'enabled' ? job.enabled : !job.enabled + ) + } + + if (scheduleModeFilter !== 'all') { + filtered = filtered.filter((job) => + scheduleModeFilter === 'cron' ? job.scheduleMode === 'cron' : job.scheduleMode === 'interval' + ) + } + + if (repoFilter !== 'all') { + filtered = filtered.filter((job) => job.repoPath === repoFilter) + } + + filtered.sort((a, b) => { + switch (sortOption) { + case 'name': + return a.name.localeCompare(b.name) + case 'repo': + return a.repoName.localeCompare(b.repoName) || a.name.localeCompare(b.name) + case 'nextRun': + default: { + const aNext = a.nextRunAt ?? Infinity + const bNext = b.nextRunAt ?? Infinity + return aNext - bNext + } + } + }) + + return filtered + }, [jobs, statusFilter, scheduleModeFilter, repoFilter, sortOption]) + + const stats = useMemo(() => { + const total = jobs.length + const enabled = jobs.filter((j) => j.enabled).length + const disabled = total - enabled + const now = Date.now() + const last24h = now - 24 * 60 * 60 * 1000 + const recentRuns = jobs.filter((j) => j.lastRunAt && j.lastRunAt > last24h) + + return { total, enabled, disabled, recentRuns: recentRuns.length } + }, [jobs]) + + const repoOptions = useMemo(() => [ + { value: 'all', label: 'All Repos', description: `${jobs.length} total jobs` }, + ...uniqueRepos.map((repo) => ({ + value: repo.path, + label: repo.name, + description: `${jobs.filter((j) => j.repoPath === repo.path).length} jobs`, + })), + ], [jobs, uniqueRepos]) + + const statusOptions = useMemo(() => [ + { value: 'all', label: 'All Status' }, + { value: 'enabled', label: 'Enabled' }, + { value: 'disabled', label: 'Disabled' }, + ], []) + + const modeOptions = useMemo(() => [ + { value: 'all', label: 'All Modes' }, + { value: 'cron', label: 'Cron' }, + { value: 'interval', label: 'Interval' }, + ], []) + + const sortOptions = useMemo(() => [ + { value: 'nextRun', label: 'Next Run' }, + { value: 'name', label: 'Name' }, + { value: 'repo', label: 'Repository' }, + ], []) + + const handleDelete = () => { + if (deleteJobId === null) { + return + } + + deleteMutation.mutate(deleteJobId, { + onSuccess: () => { + setDeleteJobId(null) + }, + }) + } + + const handleToggleEnabled = (job: ScheduleJobWithRepo) => { + updateMutation.mutate({ + jobId: job.id, + data: { enabled: !job.enabled }, + }) + } + + const handleRunNow = (job: ScheduleJobWithRepo) => { + runMutation.mutate(job.id) + } + + const handleEdit = (job: ScheduleJobWithRepo) => { + setEditingJob(job) + setDialogOpen(true) + } + + const handleCreate = () => { + setDialogOpen(false) + } + + const handleUpdate = (data: CreateScheduleJobRequest) => { + if (!editingJob) { + return + } + + updateMutation.mutate( + { + jobId: editingJob.id, + data: toUpdateScheduleRequest(data), + }, + { + onSuccess: () => { + setDialogOpen(false) + setEditingJob(null) + }, + } + ) + } + + const handleNavigateToRepo = (repoPath: string) => { + const repoId = jobs.find((j) => j.repoPath === repoPath)?.repoId + if (repoId) { + navigate(`/repos/${repoId}`) + } + } + + if (isLoading) { + return ( +
+ +
+ ) + } + + if (error) { + return ( +
+ + +

Failed to load schedules

+ +
+
+
+ ) + } + + const hasJobs = jobs.length > 0 + + return ( +
+
+ + Schedules +
+ + {stats.total} total + + + {stats.enabled} enabled + + + + + +
+
+ +
+
+ Filter by repo: + + + + + + + { + setStatusFilter('all') + setScheduleModeFilter('all') + setRepoFilter('all') + setSortOption('nextRun') + }} + className="text-xs text-muted-foreground" + > + Clear all filters + + + Status + setStatusFilter('all')} + onSelect={(e) => e.preventDefault()} + > + All Status + + {statusOptions.filter((opt) => opt.value !== 'all').map((opt) => ( + { + if (checked) { + setStatusFilter(opt.value as StatusFilter) + } else { + setStatusFilter('all') + } + }} + onSelect={(e) => e.preventDefault()} + > + {opt.label} + + ))} + + Mode + setScheduleModeFilter('all')} + onSelect={(e) => e.preventDefault()} + > + All Modes + + {modeOptions.filter((opt) => opt.value !== 'all').map((opt) => ( + { + if (checked) { + setScheduleModeFilter(opt.value as ScheduleModeFilter) + } else { + setScheduleModeFilter('all') + } + }} + onSelect={(e) => e.preventDefault()} + > + {opt.label} + + ))} + + Sort + setSortOption(v as SortOption)}> + {sortOptions.map((opt) => ( + e.preventDefault()} + > + {opt.label} + + ))} + + + +
+
+
+ Status: +
+ {statusOptions.map((opt) => ( + + ))} +
+
+
+ Mode: +
+ {modeOptions.map((opt) => ( + + ))} +
+
+
+ Sort: +
+ {sortOptions.map((opt) => ( + + ))} +
+
+
+
+ +
+ {!hasJobs ? ( +
+ + +
+ +
+
+

No schedules yet

+

+ Create schedules for your repositories to automate recurring agent work. +

+
+ +
+
+
+ ) : filteredAndSortedJobs.length === 0 ? ( +
+ + +
+ +
+
+

No matching schedules

+

+ Try adjusting your filters to see more results. +

+
+ +
+
+
+ ) : ( +
+ {filteredAndSortedJobs.map((job) => ( + navigate(`/repos/${job.repoId}/schedules`)} + > + +
+
+ +

{job.name}

+

+ {job.description || 'No description'} +

+
+ + {job.enabled ? 'Enabled' : 'Paused'} + +
+ +
+
+ + + {formatScheduleShortLabel(job)} + +
+
+ + + Next: {job.nextRunAt ? new Date(job.nextRunAt).toLocaleString() : 'Never'} + +
+ {job.lastRunAt && ( +
+ + + Last: {formatTimestamp(job.lastRunAt)} + +
+ )} +
+ +
+ + + + +
+
+
+ ))} +
+ )} +
+ + { + setDialogOpen(open) + if (!open) { + setEditingJob(null) + } + }} + job={editingJob ?? undefined} + isSaving={updateMutation.isPending} + onSubmit={editingJob ? handleUpdate : handleCreate} + /> + + !open && setDeleteJobId(null)} + onConfirm={handleDelete} + onCancel={() => setDeleteJobId(null)} + title="Delete Schedule" + description="This removes the job definition and all recorded run history for it." + isDeleting={deleteMutation.isPending} + /> +
+ ) +} diff --git a/frontend/src/pages/Repos.tsx b/frontend/src/pages/Repos.tsx index c7786fc9..184c53d7 100644 --- a/frontend/src/pages/Repos.tsx +++ b/frontend/src/pages/Repos.tsx @@ -1,13 +1,15 @@ import { useState } from "react"; +import { useNavigate } from "react-router-dom"; import { RepoList } from "@/components/repo/RepoList"; import { AddRepoDialog } from "@/components/repo/AddRepoDialog"; import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; import { Header } from "@/components/ui/header"; import { Button } from "@/components/ui/button"; -import { Plus, FolderOpen } from "lucide-react"; +import { Plus, FolderOpen, CalendarClock } from "lucide-react"; import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"; export function Repos() { + const navigate = useNavigate(); const [addRepoOpen, setAddRepoOpen] = useState(false); const [fileBrowserOpen, setFileBrowserOpen] = useState(false); @@ -31,6 +33,23 @@ export function Repos() { > + +