Add cron-based scheduling with prompt templates integration (#164)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-03-21 23:33:03 -04:00
1 parent cbd0ee2958
commit 1e863c5fc5
63 files changed
+7797 -64

No files matched your search

+1
View File
@@ -33,6 +33,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"cronstrue": "^3.13.0",
"date-fns": "^4.1.0",
"diff": "^8.0.2",
"highlight.js": "^11.11.1",
+6
View File
@@ -7,6 +7,7 @@ import { Repos } from './pages/Repos'
import { RepoDetail } from './pages/RepoDetail'
import { SessionDetail } from './pages/SessionDetail'
import { Memories } from './pages/Memories'
import { Schedules } from './pages/Schedules'
import { Login } from './pages/Login'
import { Register } from './pages/Register'
import { Setup } from './pages/Setup'
@@ -136,6 +137,11 @@ const router = createBrowserRouter([
element: <Memories />,
loader: protectedLoader,
},
{
path: '/repos/:id/schedules',
element: <Schedules />,
loader: protectedLoader,
},
],
},
])
+13
View File
@@ -1,5 +1,7 @@
import type { paths } from './opencode-types'
import { fetchWrapper } from './fetchWrapper'
import { useQuery } from '@tanstack/react-query'
import { OPENCODE_API_ENDPOINT } from '@/config'
type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json']
type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json']
@@ -248,3 +250,14 @@ export class OpenCodeClient {
export const createOpenCodeClient = (baseURL: string, directory?: string) => {
return new OpenCodeClient(baseURL, directory)
}
export const useAgents = () => {
return useQuery({
queryKey: ['opencode-agents'],
queryFn: async () => {
const client = createOpenCodeClient(OPENCODE_API_ENDPOINT)
return await client.listAgents()
},
staleTime: 5 * 60 * 1000,
})
}
+33
View File
@@ -0,0 +1,33 @@
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type {
PromptTemplate,
CreatePromptTemplateRequest,
UpdatePromptTemplateRequest,
} from '@opencode-manager/shared/types'
export async function listPromptTemplates(): Promise<{ templates: PromptTemplate[] }> {
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates`)
}
export async function createPromptTemplate(data: CreatePromptTemplateRequest): Promise<{ template: PromptTemplate }> {
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function updatePromptTemplate(id: number, data: UpdatePromptTemplateRequest): Promise<{ template: PromptTemplate }> {
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function deletePromptTemplate(id: number): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/prompt-templates/${id}`, {
method: 'DELETE',
})
}
+58
View File
@@ -0,0 +1,58 @@
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type {
CreateScheduleJobRequest,
ScheduleJob,
ScheduleRun,
UpdateScheduleJobRequest,
} from '@opencode-manager/shared/types'
export async function listRepoSchedules(repoId: number): Promise<{ jobs: ScheduleJob[] }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules`)
}
export async function getRepoSchedule(repoId: number, jobId: number): Promise<{ job: ScheduleJob }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`)
}
export async function createRepoSchedule(repoId: number, data: CreateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function updateRepoSchedule(repoId: number, jobId: number, data: UpdateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function deleteRepoSchedule(repoId: number, jobId: number): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`, {
method: 'DELETE',
})
}
export async function runRepoSchedule(repoId: number, jobId: number): Promise<{ run: ScheduleRun }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/run`, {
method: 'POST',
})
}
export async function listRepoScheduleRuns(repoId: number, jobId: number, limit: number = 20): Promise<{ runs: ScheduleRun[] }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs?limit=${limit}`)
}
export async function getRepoScheduleRun(repoId: number, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}`)
}
export async function cancelRepoScheduleRun(repoId: number, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}/cancel`, {
method: 'POST',
})
}
@@ -0,0 +1,144 @@
import type { ScheduleJob } from '@opencode-manager/shared/types'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
formatScheduleSummary,
formatTimestamp,
getJobStatusTone,
hasSkillMetadata,
} from '@/components/schedules/schedule-utils'
import { Bot, CalendarClock, Clock3, History, Loader2, Pencil, Play, Sparkles, Trash2 } from 'lucide-react'
interface JobDetailTabProps {
selectedJob: ScheduleJob | undefined
onEdit: (job: ScheduleJob) => void
onDelete: (jobId: number) => void
onToggleEnabled: () => void
onRunNow: () => void
updatePending: boolean
runPending: boolean
runningRun: boolean
isJobFetching: boolean
}
export function JobDetailTab({
selectedJob,
onEdit,
onDelete,
onToggleEnabled,
onRunNow,
updatePending,
runPending,
runningRun,
isJobFetching,
}: JobDetailTabProps) {
if (!selectedJob) {
return (
<div className="flex h-full items-center justify-center">
<div className="text-center">
<CalendarClock className="mx-auto mb-4 h-10 w-10 text-muted-foreground" />
<p className="text-lg font-medium">No job selected</p>
<p className="mt-2 text-sm text-muted-foreground">Select a job from the Jobs tab to view details</p>
</div>
</div>
)
}
return (
<div className="h-full overflow-y-auto">
<section className="overflow-hidden rounded-xl bg-card/40">
<div className="border-b border-border/60 bg-card px-3 py-4 sm:px-6 sm:py-5">
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-xl font-semibold tracking-tight">{selectedJob.name}</h3>
<Badge className={getJobStatusTone(selectedJob)}>{selectedJob.enabled ? 'Enabled' : 'Paused'}</Badge>
</div>
<p className="text-sm text-muted-foreground">{selectedJob.description || 'No description provided.'}</p>
<div className="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" /> {formatTimestamp(selectedJob.nextRunAt)}</span>
<span className="inline-flex items-center gap-1"><History className="h-3.5 w-3.5" /> Last run {formatTimestamp(selectedJob.lastRunAt)}</span>
<span className="inline-flex items-center gap-1"><CalendarClock className="h-3.5 w-3.5" /> {formatScheduleSummary(selectedJob)}</span>
<span className="inline-flex items-center gap-1"><Bot className="h-3.5 w-3.5" /> {selectedJob.agentSlug ?? 'default agent'}</span>
</div>
</div>
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm" onClick={onToggleEnabled} disabled={updatePending}>
{selectedJob.enabled ? 'Pause' : 'Enable'}
</Button>
<Button variant="outline" size="sm" onClick={() => onEdit(selectedJob)} title="Edit">
<Pencil className="h-4 w-4 sm:mr-2" />
<span className="hidden sm:inline">Edit</span>
</Button>
<Button variant="outline" size="sm" onClick={onRunNow} disabled={runPending || runningRun || isJobFetching} title={runningRun ? 'Run in progress' : isJobFetching ? 'Refreshing...' : 'Run now'}>
{runPending || isJobFetching ? <Loader2 className="h-4 w-4 sm:mr-2 animate-spin" /> : <Play className="h-4 w-4 sm:mr-2" />}
<span className="hidden sm:inline">{runningRun ? 'Run in progress' : isJobFetching ? 'Refreshing...' : 'Run now'}</span>
</Button>
<Button variant="destructive" size="sm" onClick={() => onDelete(selectedJob.id)} title="Delete">
<Trash2 className="h-4 w-4 sm:mr-2" />
<span className="hidden sm:inline">Delete</span>
</Button>
</div>
</div>
</div>
<div className="p-3 sm:p-6">
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_280px]">
<div className="space-y-4">
<section className="rounded-lg border border-border/60 bg-background/40 p-3 sm:p-4">
<div className="mb-3">
<h3 className="text-base font-medium">Execution Prompt</h3>
<p className="text-sm text-muted-foreground">Sent to OpenCode as the first message in the generated session.</p>
</div>
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6 text-foreground/90">{selectedJob.prompt}</pre>
</section>
{hasSkillMetadata(selectedJob) && (
<section className="rounded-lg border border-border/60 bg-background/40 p-3 sm:p-4">
<div className="mb-3">
<h3 className="text-base font-medium flex items-center gap-2"><Sparkles className="h-4 w-4" /> Advanced metadata</h3>
<p className="text-sm text-muted-foreground">Stored for future scheduler integrations. The current MVP does not execute against these fields yet.</p>
</div>
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6 text-foreground/90">{JSON.stringify(selectedJob.skillMetadata, null, 2)}</pre>
</section>
)}
</div>
<Card className="border-border/60 bg-background/60 shadow-none">
<CardHeader>
<CardTitle className="text-base">Execution Settings</CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<div>
<p className="text-muted-foreground">Schedule</p>
<p className="font-medium break-words">{formatScheduleSummary(selectedJob)}</p>
{selectedJob.scheduleMode === 'cron' && selectedJob.cronExpression && (
<p className="mt-1 break-all font-mono text-xs text-muted-foreground">{selectedJob.cronExpression}</p>
)}
</div>
<div>
<p className="text-muted-foreground">Agent</p>
<p className="font-medium">{selectedJob.agentSlug ?? 'Default agent'}</p>
</div>
<div>
<p className="text-muted-foreground">Model</p>
<p className="font-medium break-all">{selectedJob.model ?? 'Workspace default'}</p>
</div>
<div>
<p className="text-muted-foreground">Created</p>
<p className="font-medium">{formatTimestamp(selectedJob.createdAt)}</p>
</div>
<div>
<p className="text-muted-foreground">Updated</p>
<p className="font-medium">{formatTimestamp(selectedJob.updatedAt)}</p>
</div>
</CardContent>
</Card>
</div>
</div>
</section>
</div>
)
}
@@ -0,0 +1,43 @@
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 py-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>
)
}
@@ -0,0 +1,120 @@
import { useState, useEffect } from 'react'
import type { PromptTemplate, CreatePromptTemplateRequest } from '@opencode-manager/shared/types'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Loader2 } from 'lucide-react'
import { useCreatePromptTemplate, useUpdatePromptTemplate } from '@/hooks/usePromptTemplates'
interface PromptTemplateDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
template?: PromptTemplate
}
export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTemplateDialogProps) {
const [title, setTitle] = useState('')
const [category, setCategory] = useState('')
const [cadenceHint, setCadenceHint] = useState('')
const [suggestedName, setSuggestedName] = useState('')
const [suggestedDescription, setSuggestedDescription] = useState('')
const [description, setDescription] = useState('')
const [prompt, setPrompt] = useState('')
const createMutation = useCreatePromptTemplate()
const updateMutation = useUpdatePromptTemplate()
const isSaving = createMutation.isPending || updateMutation.isPending
useEffect(() => {
if (open) {
setTitle(template?.title ?? '')
setCategory(template?.category ?? '')
setCadenceHint(template?.cadenceHint ?? '')
setSuggestedName(template?.suggestedName ?? '')
setSuggestedDescription(template?.suggestedDescription ?? '')
setDescription(template?.description ?? '')
setPrompt(template?.prompt ?? '')
} else {
setTitle('')
setCategory('')
setCadenceHint('')
setSuggestedName('')
setSuggestedDescription('')
setDescription('')
setPrompt('')
}
}, [template, open])
const handleSubmit = () => {
const data: CreatePromptTemplateRequest = {
title: title.trim(),
category: category.trim(),
cadenceHint: cadenceHint.trim(),
suggestedName: suggestedName.trim(),
suggestedDescription: suggestedDescription.trim(),
description: description.trim(),
prompt: prompt.trim(),
}
if (template) {
updateMutation.mutate({ id: template.id, data }, { onSuccess: () => onOpenChange(false) })
} else {
createMutation.mutate(data, { onSuccess: () => onOpenChange(false) })
}
}
const isValid = title.trim() && category.trim() && cadenceHint.trim() && suggestedName.trim() && prompt.trim()
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className=" flex h-[calc(100dvh-1rem)] max-h-[calc(100dvh-1rem)] w-[calc(100vw-1rem)] max-w-2xl flex-col overflow-hidden sm:h-auto sm:max-h-[90vh]">
<DialogHeader>
<DialogTitle>{template ? 'Edit template' : 'New template'}</DialogTitle>
</DialogHeader>
<div className="flex-1 overflow-y-auto space-y-4 py-2">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="template-title">Title</Label>
<Input id="template-title" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Repo Health Report" />
</div>
<div className="space-y-2">
<Label htmlFor="template-category">Category</Label>
<Input id="template-category" value={category} onChange={(e) => setCategory(e.target.value)} placeholder="Health" />
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="template-cadence">Cadence hint</Label>
<Input id="template-cadence" value={cadenceHint} onChange={(e) => setCadenceHint(e.target.value)} placeholder="Weekly" />
</div>
<div className="space-y-2">
<Label htmlFor="template-suggested-name">Suggested job name</Label>
<Input id="template-suggested-name" value={suggestedName} onChange={(e) => setSuggestedName(e.target.value)} placeholder="Weekly repo health report" />
</div>
</div>
<div className="space-y-2">
<Label htmlFor="template-description">Description</Label>
<Input id="template-description" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Short summary shown on the template card" />
</div>
<div className="space-y-2">
<Label htmlFor="template-suggested-description">Suggested job description</Label>
<Input id="template-suggested-description" value={suggestedDescription} onChange={(e) => setSuggestedDescription(e.target.value)} placeholder="Pre-fills the schedule job description field" />
</div>
<div className="space-y-2">
<Label htmlFor="template-prompt">Prompt</Label>
<Textarea id="template-prompt" value={prompt} onChange={(e) => setPrompt(e.target.value)} className="min-h-[200px]" placeholder="The full prompt sent to the agent when the schedule runs." />
</div>
</div>
<div className="flex flex-row gap-2 pt-2 border-t border-border sm:justify-end">
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving} className="flex-1 sm:flex-none">Cancel</Button>
<Button onClick={handleSubmit} disabled={isSaving || !isValid} className="flex-1 sm:flex-none">
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
{isSaving ? 'Saving...' : template ? 'Save changes' : 'Create template'}
</Button>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,275 @@
import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown'
import { getRunTone } from '@/components/schedules/schedule-utils'
import { Ban, CheckCircle2, ChevronDown, History, Loader2, XCircle } from 'lucide-react'
interface RunHistoryTabProps {
repoId: number
selectedJob: ScheduleJob | undefined
runs: ScheduleRun[] | undefined
runsLoading: boolean
selectedRunId: number | null
onSelectRun: (id: number) => void
activeRun: ScheduleRun | null
selectedRunLoading: boolean
onCancelRun: () => void
cancelRunPending: boolean
}
interface RunDetailPanelProps {
repoId: number
activeRun: ScheduleRun | null
selectedRunLoading: boolean
onCancelRun: () => void
cancelRunPending: boolean
}
function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancelRun, cancelRunPending }: RunDetailPanelProps) {
const navigate = useNavigate()
if (selectedRunLoading && !activeRun) {
return (
<div className="flex h-full items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)
}
if (!activeRun) {
return <div className="flex h-full items-center justify-center text-sm text-muted-foreground">Select a run to inspect logs and output.</div>
}
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">
<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>
</TabsList>
</div>
{(activeRun.status === 'running' || activeRun.sessionId || activeRun.responseText) && (
<div className="flex items-center justify-between gap-2 px-3 py-2">
<div className="flex items-center gap-2">
{activeRun.sessionId && (
<Button variant="outline" size="sm" onClick={() => navigate(`/repos/${repoId}/sessions/${activeRun.sessionId}`)}>
Open session
</Button>
)}
</div>
<Button variant="outline" size="sm" onClick={onCancelRun} disabled={cancelRunPending || activeRun.status !== 'running'}>
{cancelRunPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
Cancel run
</Button>
</div>
)}
<TabsContent value="log" className="mt-0 min-h-0 flex-1 overflow-y-auto px-0 py-3 [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>
) : (
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6">{activeRun.logText ?? 'No log text captured.'}</pre>
)}
</TabsContent>
<TabsContent value="response" className="mt-0 min-h-0 flex-1 flex flex-col overflow-hidden">
{selectedRunLoading && !activeRun ? (
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
) : activeRun.responseText ? (
<div className="min-h-0 flex-1 overflow-y-auto px-0 py-2 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
<ScheduleRunMarkdown content={activeRun.responseText} />
</div>
) : (
<div className="p-3"><pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6">No assistant output captured.</pre></div>
)}
</TabsContent>
<TabsContent value="error" className="mt-0 min-h-0 flex-1 overflow-y-auto px-0 py-3 [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>
) : (
<pre className={`whitespace-pre-wrap break-words text-sm font-mono leading-6 ${activeRun.status === 'cancelled' ? 'text-muted-foreground' : 'text-red-300'}`}>{activeRun.errorText ?? 'No error recorded.'}</pre>
)}
</TabsContent>
</Tabs>
)
}
export function RunHistoryTab({
repoId,
selectedJob,
runs,
runsLoading,
selectedRunId,
onSelectRun,
activeRun,
selectedRunLoading,
onCancelRun,
cancelRunPending,
}: RunHistoryTabProps) {
const [expandedRunId, setExpandedRunId] = useState<number | null>(selectedRunId)
useEffect(() => {
setExpandedRunId(selectedRunId)
}, [selectedRunId])
function getRunStatusIcon(status: ScheduleRun['status']) {
if (status === 'completed') return <CheckCircle2 className="h-3.5 w-3.5 text-green-400" />
if (status === 'failed') return <XCircle className="h-3.5 w-3.5 text-red-400" />
if (status === 'running') return <Loader2 className="h-3.5 w-3.5 animate-spin text-blue-400" />
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 (!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">
<CardContent className="flex flex-col items-center p-8 sm:p-10 text-center">
<History className="h-10 w-10 text-muted-foreground mb-4" />
<p className="text-lg font-medium">No job selected</p>
<p className="mt-2 text-sm text-muted-foreground">Select a job from the Jobs tab to view its run history</p>
</CardContent>
</Card>
</div>
)
}
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
<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">
{/* Mobile: collapsible list (hidden on xl+) */}
<div className="xl:hidden flex flex-col min-h-0 flex-1 h-full">
<div className="min-h-0 flex-1 overflow-y-auto pt-4 pb-6 px-2 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
{runsLoading ? (
<div className="flex items-center justify-center p-6"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
) : runs?.length ? runs.map((run, index) => (
<div
key={run.id}
className={`rounded-xl border overflow-hidden transition-all bg-card ${
expandedRunId === run.id
? 'border-border/70'
: 'border-border/70'
} ${index === 0 ? 'mt-0' : 'mt-2'}`}
>
<button
type="button"
onClick={() => handleCardClick(run.id)}
className="w-full 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>
<p className="mt-0.5 text-xs text-muted-foreground">{new Date(run.startedAt).toLocaleString()}</p>
{run.errorText && (
<p className="mt-0.5 truncate text-xs text-red-400/80">{run.errorText}</p>
)}
</div>
<ChevronDown className={`h-4 w-4 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${expandedRunId === run.id ? 'rotate-180' : ''}`} />
</button>
{expandedRunId === run.id && (
<div className="border-t border-border/60 flex flex-col" style={{ maxHeight: 'calc(100vh - 200px)' }}>
<div className="flex flex-col min-h-0 flex-1 overflow-hidden">
<RunDetailPanel
repoId={repoId}
activeRun={activeRun}
selectedRunLoading={selectedRunLoading}
onCancelRun={onCancelRun}
cancelRunPending={cancelRunPending}
/>
</div>
</div>
)}
</div>
)) : (
<Alert>
<History className="h-4 w-4" />
<AlertTitle>No runs yet</AlertTitle>
<AlertDescription>Use Run now to generate the first execution record and log bundle.</AlertDescription>
</Alert>
)}
</div>
</div>
{/* Desktop: original two-column layout (hidden below xl) */}
<div className="hidden xl:block min-h-0 space-y-2 overflow-y-auto pr-1">
{runsLoading ? (
<div className="flex items-center justify-center p-6"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
) : runs?.length ? runs.map((run) => (
<button
key={run.id}
type="button"
onClick={() => onSelectRun(run.id)}
className={`w-full rounded-xl border px-4 py-3 text-left transition-all ${
selectedRunId === run.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-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>
<p className="mt-0.5 text-xs text-muted-foreground">{new Date(run.startedAt).toLocaleString()}</p>
{run.errorText && (
<p className="mt-0.5 truncate text-xs text-red-400/80">{run.errorText}</p>
)}
</button>
)) : (
<Alert>
<History className="h-4 w-4" />
<AlertTitle>No runs yet</AlertTitle>
<AlertDescription>Use Run now to generate the first execution record and log bundle.</AlertDescription>
</Alert>
)}
</div>
{/* Desktop: detail panel (hidden below xl) */}
<div className="hidden xl:flex min-h-0 flex-col overflow-hidden rounded-xl border border-border/60 bg-background/60 p-4">
<RunDetailPanel
repoId={repoId}
activeRun={activeRun}
selectedRunLoading={selectedRunLoading}
onCancelRun={onCancelRun}
cancelRunPending={cancelRunPending}
/>
</div>
</div>
</div>
)
}
@@ -0,0 +1,632 @@
import { useEffect, useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob } from '@opencode-manager/shared/types'
import { getProvidersWithModels } from '@/api/providers'
import { createOpenCodeClient } from '@/api/opencode'
import { OPENCODE_API_ENDPOINT } from '@/config'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Textarea } from '@/components/ui/textarea'
import {
buildCronExpressionFromPreset,
cronPresetOptions,
detectSchedulePreset,
formatDraftScheduleSummary,
getLocalTimeZone,
intervalOptions,
schedulePresetOptions,
type SchedulePreset,
weekdayOptions,
} from '@/components/schedules/schedule-utils'
import { Check, Info, Loader2, Pencil, Plus, Sparkles, Trash2 } from 'lucide-react'
import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates'
import { PromptTemplateDialog } from './PromptTemplateDialog'
import { DeleteDialog } from '@/components/ui/delete-dialog'
type ScheduleJobDialogProps = {
open: boolean
onOpenChange: (open: boolean) => void
job?: ScheduleJob
isSaving: boolean
onSubmit: (data: CreateScheduleJobRequest) => void
}
function InfoHint({ text }: { text: string }) {
return (
<span
title={text}
aria-label={text}
className="inline-flex h-4 w-4 items-center justify-center text-muted-foreground"
>
<Info className="h-3.5 w-3.5" />
</span>
)
}
export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit }: ScheduleJobDialogProps) {
const [schedulePreset, setSchedulePreset] = useState<SchedulePreset>('interval')
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [enabled, setEnabled] = useState(true)
const [intervalMinutes, setIntervalMinutes] = useState('60')
const [timeOfDay, setTimeOfDay] = useState('09:00')
const [hourlyMinute, setHourlyMinute] = useState('0')
const [weeklyDays, setWeeklyDays] = useState<string[]>(['1'])
const [monthlyDay, setMonthlyDay] = useState('1')
const [cronExpression, setCronExpression] = useState('0 9 * * 1-5')
const [timezone, setTimezone] = useState(getLocalTimeZone())
const [agentSlug, setAgentSlug] = useState('')
const [model, setModel] = useState('')
const [prompt, setPrompt] = useState('')
const [selectedPromptTemplateId, setSelectedPromptTemplateId] = useState<number | null>(null)
const [skillSlugs, setSkillSlugs] = useState('')
const [skillNotes, setSkillNotes] = useState('')
const [templateDialogOpen, setTemplateDialogOpen] = useState(false)
const [editingTemplate, setEditingTemplate] = useState<PromptTemplate | undefined>(undefined)
const [deletingTemplateId, setDeletingTemplateId] = useState<number | null>(null)
const { data: templates = [] } = usePromptTemplates()
const deleteTemplateMutation = useDeletePromptTemplate()
const { data: providerModels = [] } = useQuery({
queryKey: ['providers-with-models', 'schedule-dialog'],
queryFn: () => getProvidersWithModels(),
enabled: open,
staleTime: 5 * 60 * 1000,
})
const { data: agents = [] } = useQuery({
queryKey: ['opencode-agents', 'schedule-dialog'],
queryFn: async () => {
const client = createOpenCodeClient(OPENCODE_API_ENDPOINT)
return await client.listAgents()
},
enabled: open,
staleTime: 5 * 60 * 1000,
})
const { data: openCodeConfig } = useQuery({
queryKey: ['opencode-config', 'schedule-dialog'],
queryFn: async () => {
const client = createOpenCodeClient(OPENCODE_API_ENDPOINT)
return await client.getConfig()
},
enabled: open,
staleTime: 5 * 60 * 1000,
})
const modelOptions = useMemo<ComboboxOption[]>(() => {
const configuredModels: ComboboxOption[] = []
const configuredValues = new Set<string>()
for (const configModel of [openCodeConfig?.model, openCodeConfig?.small_model]) {
if (!configModel || configuredValues.has(configModel)) continue
configuredValues.add(configModel)
const [providerId, ...modelParts] = configModel.split('/')
const modelId = modelParts.join('/')
const provider = providerModels.find((p) => p.id === providerId)
const providerModel = provider?.models.find((m) => m.id === modelId)
configuredModels.push({
value: configModel,
label: providerModel?.name || modelId,
description: configModel,
group: 'Configured',
})
}
const allModels = providerModels.flatMap((provider) =>
provider.models
.filter((providerModel) => !configuredValues.has(`${provider.id}/${providerModel.id}`))
.map((providerModel) => ({
value: `${provider.id}/${providerModel.id}`,
label: providerModel.name || providerModel.id,
description: `${provider.id}/${providerModel.id}`,
group: provider.name,
})),
)
return [...configuredModels, ...allModels]
}, [providerModels, openCodeConfig])
const agentOptions = useMemo<ComboboxOption[]>(() => {
return agents.map((agent) => ({
value: agent.name,
label: agent.name,
description: agent.description,
}))
}, [agents])
useEffect(() => {
if (!open) {
return
}
setName(job?.name ?? '')
setDescription(job?.description ?? '')
setEnabled(job?.enabled ?? true)
const scheduleDefaults = detectSchedulePreset(job)
setSchedulePreset(scheduleDefaults.preset)
setIntervalMinutes(scheduleDefaults.intervalMinutes)
setTimeOfDay(scheduleDefaults.timeOfDay)
setHourlyMinute(scheduleDefaults.hourlyMinute)
setWeeklyDays(scheduleDefaults.weeklyDays)
setMonthlyDay(scheduleDefaults.monthlyDay)
setCronExpression(scheduleDefaults.cronExpression)
setTimezone(scheduleDefaults.timezone)
setAgentSlug(job?.agentSlug ?? '')
setModel(job?.model ?? '')
setPrompt(job?.prompt ?? '')
const matchingTemplate = templates.find((template) => template.prompt === (job?.prompt ?? ''))
setSelectedPromptTemplateId(matchingTemplate ? matchingTemplate.id : null)
setSkillSlugs(job?.skillMetadata?.skillSlugs.join(', ') ?? '')
setSkillNotes(job?.skillMetadata?.notes ?? '')
}, [job, open, templates])
const applyPromptTemplate = (template: PromptTemplate) => {
setSelectedPromptTemplateId(template.id)
setName(template.suggestedName)
setDescription(template.suggestedDescription)
setPrompt(template.prompt)
}
const handleSubmit = () => {
const parsedInterval = Number.parseInt(intervalMinutes, 10)
const resolvedCronExpression = buildCronExpressionFromPreset({
preset: schedulePreset,
intervalMinutes,
timeOfDay,
hourlyMinute,
weeklyDays,
monthlyDay,
cronExpression,
})
const baseFields = {
name: name.trim(),
description: description.trim() || undefined,
enabled,
agentSlug: agentSlug.trim() || undefined,
model: model.trim() || undefined,
prompt: prompt.trim(),
skillMetadata: skillSlugs.trim() || skillNotes.trim()
? {
skillSlugs: skillSlugs.split(',').map((value) => value.trim()).filter(Boolean),
notes: skillNotes.trim() || undefined,
}
: undefined,
}
if (schedulePreset !== 'interval') {
onSubmit({
...baseFields,
scheduleMode: 'cron',
cronExpression: resolvedCronExpression,
timezone: timezone.trim() || 'UTC',
})
return
}
onSubmit({
...baseFields,
scheduleMode: 'interval',
intervalMinutes: Number.isNaN(parsedInterval) ? 60 : parsedInterval,
})
}
const isScheduleConfigInvalid =
(schedulePreset === 'advanced' && (!cronExpression.trim() || !timezone.trim())) ||
((schedulePreset === 'daily' || schedulePreset === 'weekdays' || schedulePreset === 'weekly' || schedulePreset === 'monthly') && !timezone.trim()) ||
(schedulePreset === 'weekly' && weeklyDays.length === 0)
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
overlayClassName="bg-black/80"
className="flex h-dvh max-h-dvh w-full max-w-4xl flex-col gap-0 overflow-hidden border-border bg-background p-0 shadow-lg sm:h-[min(85vh,760px)] sm:max-h-[85vh] sm:w-[calc(100vw-1rem)]"
>
<DialogHeader className="shrink-0 space-y-1 px-3 sm:px-6 pt-6 pb-3 pr-14">
<DialogTitle>{job ? 'Edit schedule' : 'New schedule'}</DialogTitle>
<DialogDescription className="mt-0">
Create a reusable repo job with a visual schedule builder, manual runs, and optional advanced metadata.
</DialogDescription>
</DialogHeader>
<Tabs defaultValue="basics" className="flex min-h-0 flex-1 flex-col overflow-hidden">
<div className="border-b border-border px-3 sm:px-6 pb-3">
<TabsList className="grid h-9 w-full grid-cols-4 bg-card p-0.5">
<TabsTrigger value="basics" className="h-8 px-2 text-xs sm:text-sm data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm">General</TabsTrigger>
<TabsTrigger value="timing" className="h-8 px-2 text-xs sm:text-sm data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm">Timing</TabsTrigger>
<TabsTrigger value="prompt" className="h-8 px-2 text-xs sm:text-sm data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm">Prompt</TabsTrigger>
<TabsTrigger value="skills" className="h-8 px-2 text-xs sm:text-sm data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm">Skills</TabsTrigger>
</TabsList>
</div>
<TabsContent value="basics" className="mt-0 min-h-0 flex-1 overflow-y-auto pt-4 pb-5">
<div className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="schedule-name">Name</Label>
<Input id="schedule-name" value={name} onChange={(event) => setName(event.target.value)} placeholder="Nightly repo health check" />
</div>
<div className="space-y-2">
<Label htmlFor="schedule-description">Description</Label>
<Input id="schedule-description" value={description} onChange={(event) => setDescription(event.target.value)} placeholder="What this job checks or produces" />
</div>
</div>
<div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_220px] sm:items-end">
<div className="space-y-2">
<Label htmlFor="schedule-agent">Agent slug</Label>
<Combobox
value={agentSlug}
onChange={setAgentSlug}
options={agentOptions}
placeholder="Select an agent"
allowCustomValue
showClear
/>
</div>
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="schedule-model">Model override</Label>
<InfoHint text="Pick from detected OpenCode models or type a custom provider/model value." />
</div>
<Combobox
value={model}
onChange={setModel}
options={modelOptions}
placeholder="Workspace default"
allowCustomValue
showClear
/>
</div>
</div>
<div className="rounded-lg border border-border bg-card p-4">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2">
<p className="text-sm font-medium">Enabled</p>
<InfoHint text="Auto-run this job on its schedule while still allowing manual runs from the dashboard." />
</div>
<Switch checked={enabled} onCheckedChange={setEnabled} />
</div>
</div>
</div>
</TabsContent>
<TabsContent value="timing" className="px-3 mt-0 min-h-0 flex-1 overflow-y-auto sm:px-6 pt-4 pb-5">
<div className="space-y-4">
<div className="space-y-3 rounded-lg border border-border bg-card p-4">
<div>
<Label>Repeat</Label>
<p className="mt-1 text-xs text-muted-foreground">Use a simple scheduler builder by default. Advanced cron is still available if you need it.</p>
</div>
<div className="flex flex-wrap gap-2">
{schedulePresetOptions.map((option) => (
<Button
key={option.value}
type="button"
variant={schedulePreset === option.value ? 'default' : 'outline'}
size="sm"
onClick={() => setSchedulePreset(option.value)}
>
{option.label}
</Button>
))}
</div>
</div>
{schedulePreset === 'interval' ? (
<div className="space-y-3 rounded-lg border border-border bg-card p-4">
<div className="flex items-center justify-between gap-3">
<Label htmlFor="schedule-interval">Run every</Label>
<Input
id="schedule-interval"
type="number"
min={5}
max={10080}
value={intervalMinutes}
onChange={(event) => setIntervalMinutes(event.target.value)}
className="w-28"
/>
</div>
<div className="flex flex-wrap gap-2">
{intervalOptions.map((option) => (
<Button key={option.value} type="button" variant={intervalMinutes === String(option.value) ? 'default' : 'outline'} size="sm" onClick={() => setIntervalMinutes(String(option.value))}>
{option.label}
</Button>
))}
</div>
</div>
) : schedulePreset === 'hourly' ? (
<div className="grid gap-4 rounded-lg border border-border bg-card p-4 sm:grid-cols-[120px_minmax(0,1fr)] sm:items-end">
<div className="space-y-2">
<Label htmlFor="schedule-hourly-minute">Minute</Label>
<Input
id="schedule-hourly-minute"
type="number"
min={0}
max={59}
value={hourlyMinute}
onChange={(event) => setHourlyMinute(event.target.value)}
/>
</div>
<p className="text-sm text-muted-foreground">Run every hour at the selected minute mark.</p>
</div>
) : schedulePreset === 'daily' || schedulePreset === 'weekdays' ? (
<div className="grid gap-4 rounded-lg border border-border bg-card p-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="schedule-time">Time</Label>
<Input id="schedule-time" type="time" value={timeOfDay} onChange={(event) => setTimeOfDay(event.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="schedule-timezone">Timezone</Label>
<Input id="schedule-timezone" value={timezone} onChange={(event) => setTimezone(event.target.value)} placeholder="Detected from browser" />
</div>
</div>
) : schedulePreset === 'weekly' ? (
<div className="space-y-4 rounded-lg border border-border bg-card p-4">
<div className="space-y-2">
<Label>Days</Label>
<div className="flex flex-wrap gap-2">
{weekdayOptions.map((option) => {
const selected = weeklyDays.includes(option.value)
return (
<Button
key={option.value}
type="button"
variant={selected ? 'default' : 'outline'}
size="sm"
onClick={() => setWeeklyDays((current) => selected ? current.filter((value) => value !== option.value) : [...current, option.value])}
>
{option.label}
</Button>
)
})}
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="schedule-weekly-time">Time</Label>
<Input id="schedule-weekly-time" type="time" value={timeOfDay} onChange={(event) => setTimeOfDay(event.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="schedule-weekly-timezone">Timezone</Label>
<Input id="schedule-weekly-timezone" value={timezone} onChange={(event) => setTimezone(event.target.value)} placeholder="Detected from browser" />
</div>
</div>
</div>
) : schedulePreset === 'monthly' ? (
<div className="space-y-4 rounded-lg border border-border bg-card p-4">
<div className="grid gap-4 sm:grid-cols-3">
<div className="space-y-2">
<Label htmlFor="schedule-monthly-day">Day</Label>
<Input
id="schedule-monthly-day"
type="number"
min={1}
max={31}
value={monthlyDay}
onChange={(event) => setMonthlyDay(event.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="schedule-monthly-time">Time</Label>
<Input id="schedule-monthly-time" type="time" value={timeOfDay} onChange={(event) => setTimeOfDay(event.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="schedule-monthly-timezone">Timezone</Label>
<Input id="schedule-monthly-timezone" value={timezone} onChange={(event) => setTimezone(event.target.value)} placeholder="Detected from browser" />
</div>
</div>
</div>
) : (
<div className="space-y-4 rounded-lg border border-border bg-card p-4">
<div className="space-y-2">
<Label htmlFor="schedule-cron">Cron expression</Label>
<Input
id="schedule-cron"
value={cronExpression}
onChange={(event) => setCronExpression(event.target.value)}
placeholder="0 9 * * 1-5"
className="font-mono"
/>
<p className="text-xs text-muted-foreground">Examples: `0 9 * * 1-5` weekdays at 9 AM, `30 6 1 * *` monthly on the 1st at 6:30 AM.</p>
</div>
<div className="space-y-2">
<Label htmlFor="schedule-timezone">Timezone</Label>
<Input
id="schedule-timezone"
value={timezone}
onChange={(event) => setTimezone(event.target.value)}
placeholder="Detected from browser"
/>
</div>
<div className="flex flex-wrap gap-2">
{cronPresetOptions.map((option) => (
<Button key={option.value} type="button" variant="outline" size="sm" onClick={() => setCronExpression(option.value)}>
{option.label}
</Button>
))}
</div>
</div>
)}
<div className="rounded-lg border border-border bg-muted/40 p-4">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Schedule Preview</p>
<p className="mt-2 text-sm font-medium break-words">{formatDraftScheduleSummary({ preset: schedulePreset, intervalMinutes, timeOfDay, hourlyMinute, weeklyDays, monthlyDay, cronExpression, timezone })}</p>
{schedulePreset !== 'interval' && (
<p className="mt-2 text-xs text-muted-foreground font-mono break-all">
{buildCronExpressionFromPreset({ preset: schedulePreset, intervalMinutes, timeOfDay, hourlyMinute, weeklyDays, monthlyDay, cronExpression })}
</p>
)}
</div>
</div>
</TabsContent>
<TabsContent value="prompt" className="mt-0 min-h-0 flex-1 overflow-y-auto px-3 pt-4 pb-5 sm:px-4">
<div className="space-y-4">
<div className="space-y-2">
<div className="flex items-center justify-center gap-2">
<Label>Prompt templates</Label>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 gap-1 text-xs"
onClick={() => { setEditingTemplate(undefined); setTemplateDialogOpen(true) }}
>
<Plus className="h-3 w-3" />
New
</Button>
</div>
<div className="grid gap-3 lg:grid-cols-2">
{templates.map((template) => {
const isSelected = selectedPromptTemplateId === template.id
return (
<div key={template.id} className="relative group">
<button
type="button"
onClick={() => applyPromptTemplate(template)}
className={`w-full rounded-xl border-2 p-4 text-left transition-all ${
isSelected
? 'border-primary bg-primary/10 ring-2 ring-primary/30'
: 'border-border bg-card hover:bg-accent/40'
}`}
>
<div className="flex flex-wrap items-center gap-2">
<Badge className="text-[10px] uppercase tracking-wide border-transparent bg-orange-500 text-white">
{template.category}
</Badge>
<Badge className="text-[10px] uppercase tracking-wide border-transparent bg-slate-600 text-white">
{template.cadenceHint}
</Badge>
</div>
<div className="mt-3">
<p className="text-sm font-semibold">{template.title}</p>
<p className="mt-1 text-xs text-muted-foreground">{template.description}</p>
</div>
<p className="mt-3 text-xs text-muted-foreground line-clamp-3">{template.suggestedDescription}</p>
{isSelected && (
<div className="absolute top-2 right-2 h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</button>
<div className={`absolute top-2 right-10 flex gap-1 transition-opacity ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}>
<Button
type="button"
variant="ghost"
size="icon"
className="h-6 w-6"
onClick={(e) => { e.stopPropagation(); setEditingTemplate(template); setTemplateDialogOpen(true) }}
>
<Pencil className="h-3 w-3" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="h-6 w-6 text-destructive hover:text-destructive"
onClick={(e) => { e.stopPropagation(); setDeletingTemplateId(template.id) }}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
)
})}
</div>
</div>
<div className="space-y-2">
<Label htmlFor="schedule-prompt">Prompt</Label>
<Textarea
id="schedule-prompt"
value={prompt}
onChange={(event) => {
setPrompt(event.target.value)
setSelectedPromptTemplateId(null)
}}
className="min-h-[320px]"
placeholder="Review the repo, summarize notable risks, and open a session I can inspect later."
/>
</div>
<p className="text-xs text-muted-foreground">
This prompt becomes the first message sent to the agent when the schedule runs.
</p>
</div>
</TabsContent>
<TabsContent value="skills" className="mt-0 min-h-0 flex-1 overflow-y-auto px-6 pt-4 pb-5">
<div className="space-y-4">
<section className="rounded-lg border border-border bg-card p-4">
<div className="space-y-1">
<h3 className="text-base font-medium flex items-center gap-2"><Sparkles className="h-4 w-4" /> Optional future integrations</h3>
<p className="text-sm text-muted-foreground">You can ignore this for now. These fields are stored for future skill-aware scheduling, but the current MVP does not use them during execution.</p>
</div>
</section>
<details className="group rounded-lg border border-dashed border-border bg-card/50 p-4">
<summary className="cursor-pointer list-none text-sm font-medium">Edit optional skill metadata</summary>
<div className="mt-4 space-y-3">
<div className="space-y-2">
<Label htmlFor="schedule-skills">Skill tags</Label>
<Input id="schedule-skills" value={skillSlugs} onChange={(event) => setSkillSlugs(event.target.value)} placeholder="nextjs, database-tuning" />
</div>
<div className="space-y-2">
<Label htmlFor="schedule-skill-notes">Notes</Label>
<Textarea id="schedule-skill-notes" value={skillNotes} onChange={(event) => setSkillNotes(event.target.value)} placeholder="Optional notes for a future skill-aware scheduler." />
</div>
</div>
</details>
</div>
</TabsContent>
</Tabs>
<div className="mt-0 shrink-0 border-t border-border px-3 sm:px-6 py-4 flex flex-row gap-2 sm:justify-end">
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving} className="flex-1 sm:flex-none">Cancel</Button>
<Button onClick={handleSubmit} disabled={isSaving || !name.trim() || !prompt.trim() || isScheduleConfigInvalid} className="flex-1 sm:flex-none">
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
{isSaving ? 'Saving...' : job ? 'Save changes' : 'Create schedule'}
</Button>
</div>
</DialogContent>
<PromptTemplateDialog
open={templateDialogOpen}
onOpenChange={setTemplateDialogOpen}
template={editingTemplate}
/>
<DeleteDialog
open={deletingTemplateId !== null}
onOpenChange={(open) => { if (!open && !deleteTemplateMutation.isPending) setDeletingTemplateId(null) }}
onConfirm={() => {
if (deletingTemplateId !== null) {
deleteTemplateMutation.mutate(deletingTemplateId, {
onSuccess: () => setDeletingTemplateId(null),
})
}
}}
onCancel={() => { if (!deleteTemplateMutation.isPending) setDeletingTemplateId(null) }}
title="Delete template"
description="Are you sure you want to delete this template?"
isDeleting={deleteTemplateMutation.isPending}
/>
</Dialog>
)
}
@@ -0,0 +1,25 @@
import ReactMarkdown from 'react-markdown'
import rehypeHighlight from 'rehype-highlight'
import rehypeRaw from 'rehype-raw'
import remarkGfm from 'remark-gfm'
import { markdownComponents } from '@/components/file-browser/MarkdownComponents'
type ScheduleRunMarkdownProps = {
content: string
}
export function ScheduleRunMarkdown({ content }: ScheduleRunMarkdownProps) {
return (
<div className="overflow-hidden">
<div className="prose prose-invert prose-enhanced max-w-none break-words text-foreground leading-snug">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeHighlight, rehypeRaw]}
components={markdownComponents}
>
{content}
</ReactMarkdown>
</div>
</div>
)
}
@@ -0,0 +1,5 @@
export { JobsTab } from './JobsTab'
export { JobDetailTab } from './JobDetailTab'
export { RunHistoryTab } from './RunHistoryTab'
export { ScheduleJobDialog } from './ScheduleJobDialog'
export { ScheduleRunMarkdown } from './ScheduleRunMarkdown'
@@ -0,0 +1,352 @@
import cronstrue from 'cronstrue'
import { formatDistanceToNow } from 'date-fns'
import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRun, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
export const intervalOptions = [
{ label: '15m', value: 15 },
{ label: '30m', value: 30 },
{ label: '1h', value: 60 },
{ label: '4h', value: 240 },
{ label: '1d', value: 1440 },
]
export const cronPresetOptions = [
{ label: 'Weekdays 9 AM', value: '0 9 * * 1-5' },
{ label: 'Daily 9 AM', value: '0 9 * * *' },
{ label: 'Twice daily', value: '0 9,17 * * *' },
{ label: 'Mondays 8 AM', value: '0 8 * * 1' },
]
export const schedulePresetOptions = [
{ label: 'Interval', value: 'interval' },
{ label: 'Hourly', value: 'hourly' },
{ label: 'Daily', value: 'daily' },
{ label: 'Weekdays', value: 'weekdays' },
{ label: 'Weekly', value: 'weekly' },
{ label: 'Monthly', value: 'monthly' },
{ label: 'Advanced', value: 'advanced' },
] as const
export const weekdayOptions = [
{ label: 'Mon', value: '1' },
{ label: 'Tue', value: '2' },
{ label: 'Wed', value: '3' },
{ label: 'Thu', value: '4' },
{ label: 'Fri', value: '5' },
{ label: 'Sat', value: '6' },
{ label: 'Sun', value: '0' },
] as const
export type SchedulePreset = typeof schedulePresetOptions[number]['value']
export function getLocalTimeZone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
} catch {
return 'UTC'
}
}
function isNumericToken(value: string): boolean {
return /^\d+$/.test(value)
}
function parseTimeValue(value: string): { hour: number; minute: number } {
const [hourValue = '9', minuteValue = '0'] = value.split(':')
const hour = Number.parseInt(hourValue, 10)
const minute = Number.parseInt(minuteValue, 10)
return {
hour: Number.isNaN(hour) ? 9 : Math.min(Math.max(hour, 0), 23),
minute: Number.isNaN(minute) ? 0 : Math.min(Math.max(minute, 0), 59),
}
}
function toTimeValue(hour: number, minute: number): string {
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
}
function expandDayOfWeekExpression(expression: string): string[] | null {
const days = new Set<string>()
for (const token of expression.split(',')) {
const trimmedToken = token.trim()
if (!trimmedToken) {
continue
}
if (isNumericToken(trimmedToken)) {
const normalized = trimmedToken === '7' ? '0' : trimmedToken
if (!weekdayOptions.some((option) => option.value === normalized)) {
return null
}
days.add(normalized)
continue
}
const rangeMatch = trimmedToken.match(/^(\d)-(\d)$/)
if (rangeMatch) {
const start = rangeMatch[1] === '7' ? 0 : Number.parseInt(rangeMatch[1], 10)
const end = rangeMatch[2] === '7' ? 0 : Number.parseInt(rangeMatch[2], 10)
if (start > end) {
return null
}
for (let value = start; value <= end; value += 1) {
days.add(String(value))
}
continue
}
return null
}
return weekdayOptions.filter((option) => days.has(option.value)).map((option) => option.value)
}
function sortWeekdayValues(values: string[]): string[] {
const order = new Map<string, number>(weekdayOptions.map((option, index) => [option.value, index]))
return [...new Set(values)].sort((left, right) => (order.get(left) ?? 99) - (order.get(right) ?? 99))
}
export function detectSchedulePreset(job?: ScheduleJob): {
preset: SchedulePreset
intervalMinutes: string
timeOfDay: string
hourlyMinute: string
weeklyDays: string[]
monthlyDay: string
cronExpression: string
timezone: string
} {
const defaultTimezone = job?.timezone ?? getLocalTimeZone()
const defaults = {
preset: 'interval' as SchedulePreset,
intervalMinutes: String(job?.intervalMinutes ?? 60),
timeOfDay: '09:00',
hourlyMinute: '0',
weeklyDays: ['1'],
monthlyDay: '1',
cronExpression: job?.cronExpression ?? '0 9 * * 1-5',
timezone: defaultTimezone,
}
if (!job || job.scheduleMode === 'interval') {
return defaults
}
const expression = job.cronExpression?.trim() ?? ''
const fields = expression.split(/\s+/)
if (fields.length !== 5) {
return { ...defaults, preset: 'advanced', cronExpression: expression || defaults.cronExpression }
}
const [minute, hour, dayOfMonth, month, dayOfWeek] = fields
if (!isNumericToken(minute)) {
return { ...defaults, preset: 'advanced', cronExpression: expression }
}
if (month === '*' && hour === '*' && dayOfMonth === '*' && dayOfWeek === '*') {
return {
...defaults,
preset: 'hourly',
hourlyMinute: minute,
cronExpression: expression,
}
}
if (!isNumericToken(hour)) {
return { ...defaults, preset: 'advanced', cronExpression: expression }
}
const timeOfDay = toTimeValue(Number.parseInt(hour, 10), Number.parseInt(minute, 10))
if (month === '*' && dayOfMonth === '*' && dayOfWeek === '*') {
return { ...defaults, preset: 'daily', timeOfDay, cronExpression: expression }
}
if (month === '*' && dayOfMonth === '*' && dayOfWeek === '1-5') {
return { ...defaults, preset: 'weekdays', timeOfDay, cronExpression: expression, weeklyDays: ['1', '2', '3', '4', '5'] }
}
if (month === '*' && dayOfMonth === '*') {
const weeklyDays = expandDayOfWeekExpression(dayOfWeek)
if (weeklyDays && weeklyDays.length > 0) {
return { ...defaults, preset: 'weekly', timeOfDay, weeklyDays, cronExpression: expression }
}
}
if (month === '*' && dayOfWeek === '*' && isNumericToken(dayOfMonth)) {
return {
...defaults,
preset: 'monthly',
timeOfDay,
monthlyDay: dayOfMonth,
cronExpression: expression,
}
}
return { ...defaults, preset: 'advanced', timeOfDay, cronExpression: expression }
}
export function buildCronExpressionFromPreset(input: {
preset: SchedulePreset
intervalMinutes?: string
timeOfDay: string
hourlyMinute: string
weeklyDays: string[]
monthlyDay: string
cronExpression: string
}): string {
const { hour, minute } = parseTimeValue(input.timeOfDay)
switch (input.preset) {
case 'hourly':
return `${Math.min(Math.max(Number.parseInt(input.hourlyMinute, 10) || 0, 0), 59)} * * * *`
case 'daily':
return `${minute} ${hour} * * *`
case 'weekdays':
return `${minute} ${hour} * * 1-5`
case 'weekly':
return `${minute} ${hour} * * ${sortWeekdayValues(input.weeklyDays).join(',') || '1'}`
case 'monthly':
return `${minute} ${hour} ${Math.min(Math.max(Number.parseInt(input.monthlyDay, 10) || 1, 1), 31)} * *`
case 'advanced':
return input.cronExpression.trim()
default:
return input.cronExpression.trim()
}
}
export function formatIntervalLabel(intervalMinutes: number | null): string {
if (!intervalMinutes) {
return 'Custom interval'
}
if (intervalMinutes % 1440 === 0) {
const days = intervalMinutes / 1440
return `Every ${days} day${days === 1 ? '' : 's'}`
}
if (intervalMinutes % 60 === 0) {
const hours = intervalMinutes / 60
return `Every ${hours} hour${hours === 1 ? '' : 's'}`
}
return `Every ${intervalMinutes} minute${intervalMinutes === 1 ? '' : 's'}`
}
export function formatCronHumanText(cronExpression: string | null): string | null {
if (!cronExpression) {
return null
}
try {
return cronstrue.toString(cronExpression, {
throwExceptionOnParseError: true,
use24HourTimeFormat: false,
})
} catch {
return null
}
}
export function formatScheduleSummary(job: ScheduleJob): string {
if (job.scheduleMode === 'cron') {
return `${formatCronHumanText(job.cronExpression) ?? (job.cronExpression ?? 'Custom cron')}${job.timezone ? ` - ${job.timezone}` : ''}`
}
return formatIntervalLabel(job.intervalMinutes)
}
export function formatScheduleShortLabel(job: ScheduleJob): string {
if (job.scheduleMode === 'cron') {
return 'Cron schedule'
}
return formatIntervalLabel(job.intervalMinutes)
}
export function formatDraftScheduleSummary(input: {
preset: SchedulePreset
intervalMinutes: string
timeOfDay: string
hourlyMinute: string
weeklyDays: string[]
monthlyDay: string
cronExpression: string
timezone: string
}): string {
if (input.preset === 'interval') {
const parsedInterval = Number.parseInt(input.intervalMinutes, 10)
return formatIntervalLabel(Number.isNaN(parsedInterval) ? null : parsedInterval)
}
const builtCronExpression = buildCronExpressionFromPreset(input)
const humanText = formatCronHumanText(builtCronExpression)
return builtCronExpression
? `${humanText ?? builtCronExpression} - ${input.timezone.trim() || 'UTC'}`
: 'Choose a schedule'
}
export function toUpdateScheduleRequest(data: CreateScheduleJobRequest): UpdateScheduleJobRequest {
if (data.scheduleMode === 'cron') {
return {
...data,
description: data.description ?? null,
agentSlug: data.agentSlug ?? null,
model: data.model ?? null,
intervalMinutes: null,
}
}
return {
...data,
description: data.description ?? null,
agentSlug: data.agentSlug ?? null,
model: data.model ?? null,
cronExpression: null,
timezone: null,
}
}
export function formatTimestamp(value: number | null): string {
if (!value) {
return 'Never'
}
return `${new Date(value).toLocaleString()} (${formatDistanceToNow(value, { addSuffix: true })})`
}
export function getRunTone(run: ScheduleRun): string {
if (run.status === 'completed') {
return 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30'
}
if (run.status === 'failed') {
return 'bg-red-500/15 text-red-300 border-red-500/30'
}
if (run.status === 'cancelled') {
return 'bg-slate-500/15 text-slate-300 border-slate-500/30'
}
return 'bg-amber-500/15 text-amber-300 border-amber-500/30'
}
export function getJobStatusTone(job: ScheduleJob): string {
return job.enabled
? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20'
: 'bg-muted text-muted-foreground border-border'
}
export function hasSkillMetadata(job?: ScheduleJob | null): boolean {
if (!job?.skillMetadata) {
return false
}
return job.skillMetadata.skillSlugs.length > 0 || Boolean(job.skillMetadata.notes?.trim())
}
+1 -1
View File
@@ -216,7 +216,7 @@ function HeaderMobileDropdown({ children, className }: { children: ReactNode; cl
{totalPending > 0 && children && <DropdownMenuSeparator />}
{children}
{children && <DropdownMenuSeparator />}
<DropdownMenuItem onClick={open} className="gap-2">
<DropdownMenuItem onClick={open} className="gap-2 bg-muted">
<Settings className="w-4 h-4" />
<span>Settings</span>
</DropdownMenuItem>
+1 -1
View File
@@ -44,7 +44,7 @@ const TabsContent = React.forwardRef<
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
"px-2 mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
+62
View File
@@ -0,0 +1,62 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { CreatePromptTemplateRequest, UpdatePromptTemplateRequest } from '@opencode-manager/shared/types'
import {
listPromptTemplates,
createPromptTemplate,
updatePromptTemplate,
deletePromptTemplate,
} from '@/api/prompt-templates'
import { showToast } from '@/lib/toast'
export function usePromptTemplates() {
return useQuery({
queryKey: ['prompt-templates'],
queryFn: async () => {
const response = await listPromptTemplates()
return response.templates
},
})
}
export function useCreatePromptTemplate() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (data: CreatePromptTemplateRequest) => createPromptTemplate(data).then(r => r.template),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['prompt-templates'] })
showToast.success('Template created')
},
onError: (error) => {
showToast.error(`Failed to create template: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useUpdatePromptTemplate() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ id, data }: { id: number; data: UpdatePromptTemplateRequest }) =>
updatePromptTemplate(id, data).then(r => r.template),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['prompt-templates'] })
showToast.success('Template updated')
},
onError: (error) => {
showToast.error(`Failed to update template: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useDeletePromptTemplate() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (id: number) => deletePromptTemplate(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['prompt-templates'] })
showToast.success('Template deleted')
},
onError: (error) => {
showToast.error(`Failed to delete template: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
+156
View File
@@ -0,0 +1,156 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
import {
cancelRepoScheduleRun,
createRepoSchedule,
deleteRepoSchedule,
getRepoSchedule,
getRepoScheduleRun,
listRepoScheduleRuns,
listRepoSchedules,
runRepoSchedule,
updateRepoSchedule,
} from '@/api/schedules'
import { showToast } from '@/lib/toast'
export function useRepoSchedules(repoId: number | undefined) {
return useQuery({
queryKey: ['repo-schedules', repoId],
queryFn: async () => {
const response = await listRepoSchedules(repoId!)
return response.jobs
},
enabled: repoId !== undefined,
refetchInterval: 5000,
})
}
export function useRepoSchedule(repoId: number | undefined, jobId: number | null) {
return useQuery({
queryKey: ['repo-schedule', repoId, jobId],
queryFn: async () => {
const response = await getRepoSchedule(repoId!, jobId!)
return response.job
},
enabled: repoId !== undefined && jobId !== null,
refetchInterval: jobId !== null ? 5000 : false,
})
}
export function useRepoScheduleRuns(repoId: number | undefined, jobId: number | null, limit: number = 20) {
return useQuery({
queryKey: ['repo-schedule-runs', repoId, jobId, limit],
queryFn: async () => {
const response = await listRepoScheduleRuns(repoId!, jobId!, limit)
return response.runs
},
enabled: repoId !== undefined && jobId !== null,
refetchInterval: jobId !== null ? 5000 : false,
})
}
export function useRepoScheduleRun(repoId: number | undefined, jobId: number | null, runId: number | null) {
return useQuery({
queryKey: ['repo-schedule-run', repoId, jobId, runId],
queryFn: async () => {
const response = await getRepoScheduleRun(repoId!, jobId!, runId!)
return response.run
},
enabled: repoId !== undefined && jobId !== null && runId !== null,
refetchInterval: runId !== null ? 5000 : false,
})
}
export function useCreateRepoSchedule(repoId: number | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (data: CreateScheduleJobRequest) => {
const response = await createRepoSchedule(repoId!, data)
return response.job
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
showToast.success('Schedule created')
},
onError: (error) => {
showToast.error(`Failed to create schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useUpdateRepoSchedule(repoId: number | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ jobId, data }: { jobId: number; data: UpdateScheduleJobRequest }) => {
const response = await updateRepoSchedule(repoId!, jobId, data)
return response.job
},
onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule', repoId, variables.jobId] })
showToast.success('Schedule updated')
},
onError: (error) => {
showToast.error(`Failed to update schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useDeleteRepoSchedule(repoId: number | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (jobId: number) => deleteRepoSchedule(repoId!, jobId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
showToast.success('Schedule deleted')
},
onError: (error) => {
showToast.error(`Failed to delete schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useRunRepoSchedule(repoId: number | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (jobId: number) => {
const response = await runRepoSchedule(repoId!, jobId)
return response.run
},
onSuccess: (run) => {
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', repoId, run.jobId] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule', repoId, run.jobId] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule-run', repoId, run.jobId, run.id] })
showToast.success(run.status === 'running' ? 'Schedule started' : 'Schedule run completed')
},
onError: (error) => {
showToast.error(`Failed to run schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useCancelRepoScheduleRun(repoId: number | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ jobId, runId }: { jobId: number; runId: number }) => {
const response = await cancelRepoScheduleRun(repoId!, jobId, runId)
return response.run
},
onSuccess: (run) => {
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', repoId, run.jobId] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule', repoId, run.jobId] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule-run', repoId, run.jobId, run.id] })
showToast.success('Schedule run cancelled')
},
onError: (error) => {
showToast.error(`Failed to cancel schedule run: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
+19 -7
View File
@@ -16,7 +16,7 @@ import { useSwipeBack } from "@/hooks/useMobile";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Plug, FolderOpen, Plus, GitBranch, GitCommitHorizontal, ShieldOff, Brain, Loader2 } from "lucide-react";
import { Plug, FolderOpen, Plus, GitBranch, GitCommitHorizontal, ShieldOff, Brain, Loader2, CalendarClock } from "lucide-react";
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
import { invalidateConfigCaches } from "@/lib/queryInvalidation";
@@ -184,24 +184,36 @@ export function RepoDetail() {
<span className="hidden sm:inline">Memory</span>
</Button>
)}
<Button
variant="outline"
onClick={() => navigate(`/repos/${repoId}/schedules`)}
size="sm"
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
>
<CalendarClock className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Schedules</span>
</Button>
<Header.MobileDropdown>
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
<FolderOpen className="w-4 h-4 mr-2" /> Files
</DropdownMenuItem>
{memoryPluginStatus?.memoryPluginEnabled && (
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
<Brain className="w-4 h-4 mr-2" /> Memory
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
<Plug className="w-4 h-4 mr-2" /> MCP
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
<FolderOpen className="w-4 h-4 mr-2" /> Files
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
</DropdownMenuItem>
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/schedules`)}>
<CalendarClock className="w-4 h-4 mr-2" /> Schedules
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
</DropdownMenuItem>
</Header.MobileDropdown>
<Button
onClick={() => handleCreateSession()}
+340
View File
@@ -0,0 +1,340 @@
import { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
import { getRepo } from '@/api/repos'
import {
useCancelRepoScheduleRun,
useCreateRepoSchedule,
useDeleteRepoSchedule,
useRepoSchedule,
useRepoScheduleRun,
useRepoScheduleRuns,
useRepoSchedules,
useRunRepoSchedule,
useUpdateRepoSchedule,
} from '@/hooks/useSchedules'
import { ScheduleJobDialog } from '@/components/schedules/ScheduleJobDialog'
import { JobsTab, JobDetailTab, RunHistoryTab } from '@/components/schedules'
import { toUpdateScheduleRequest, getJobStatusTone } from '@/components/schedules/schedule-utils'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { getRepoDisplayName, cn } from '@/lib/utils'
import { CalendarClock, History, Info, Loader2, Plus } from 'lucide-react'
export function Schedules() {
const { id } = useParams<{ id: string }>()
const repoId = id ? Number(id) : undefined
const [selectedJobId, setSelectedJobId] = useState<number | null>(null)
const [selectedRunId, setSelectedRunId] = useState<number | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [editingJob, setEditingJob] = useState<ScheduleJob | undefined>()
const [deleteJobId, setDeleteJobId] = useState<number | null>(null)
const [activeTab, setActiveTab] = useState<'jobs' | 'detail' | 'runs'>('jobs')
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId!),
enabled: repoId !== undefined,
})
const { data: jobs, isLoading: jobsLoading } = useRepoSchedules(repoId)
const { data: selectedJob, isFetching: isJobFetching } = useRepoSchedule(repoId, selectedJobId)
const { data: runs, isLoading: runsLoading } = useRepoScheduleRuns(repoId, selectedJobId, 30)
const { data: selectedRunDetails, isLoading: selectedRunLoading } = useRepoScheduleRun(repoId, selectedJobId, selectedRunId)
const createMutation = useCreateRepoSchedule(repoId)
const updateMutation = useUpdateRepoSchedule(repoId)
const deleteMutation = useDeleteRepoSchedule(repoId)
const runMutation = useRunRepoSchedule(repoId)
const cancelRunMutation = useCancelRepoScheduleRun(repoId)
useEffect(() => {
if (!jobs?.length) {
setSelectedJobId(null)
setActiveTab('jobs')
return
}
const stillExists = selectedJobId !== null && jobs.some((job) => job.id === selectedJobId)
if (!stillExists) {
setSelectedJobId(jobs[0]?.id ?? null)
setActiveTab('jobs')
}
}, [jobs, selectedJobId])
useEffect(() => {
if (!runs?.length) {
setSelectedRunId(null)
return
}
const stillExists = selectedRunId !== null && runs.some((run) => run.id === selectedRunId)
if (!stillExists) {
setSelectedRunId(runs[0]?.id ?? null)
}
}, [runs, selectedRunId])
const activeRunSummary = useMemo(() => runs?.find((run) => run.id === selectedRunId) ?? null, [runs, selectedRunId])
const activeRun = selectedRunDetails ?? activeRunSummary
const runningRun = useMemo(() => runs?.find((run) => run.status === 'running') ?? null, [runs])
if (repoLoading || jobsLoading) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
)
}
if (!repo || repoId === undefined) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<p className="text-muted-foreground">Repository not found</p>
</div>
)
}
const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath)
const enabledCount = jobs?.filter((job) => job.enabled).length ?? 0
const hasJobs = (jobs?.length ?? 0) > 0
const handleCreate = (data: CreateScheduleJobRequest) => {
createMutation.mutate(data, {
onSuccess: (job) => {
setSelectedJobId(job.id)
setDialogOpen(false)
setEditingJob(undefined)
},
})
}
const handleUpdate = (data: CreateScheduleJobRequest) => {
if (!editingJob) {
return
}
updateMutation.mutate({
jobId: editingJob.id,
data: toUpdateScheduleRequest(data),
}, {
onSuccess: () => {
setDialogOpen(false)
setEditingJob(undefined)
},
})
}
const handleDelete = () => {
if (deleteJobId === null) {
return
}
deleteMutation.mutate(deleteJobId, {
onSuccess: () => {
if (selectedJobId === deleteJobId) {
setSelectedJobId(null)
}
setDeleteJobId(null)
},
})
}
const handleToggleEnabled = () => {
if (!selectedJob) {
return
}
updateMutation.mutate({
jobId: selectedJob.id,
data: { enabled: !selectedJob.enabled },
})
}
const handleRunNow = () => {
if (!selectedJob) {
return
}
runMutation.mutate(selectedJob.id, {
onSuccess: (run) => {
setSelectedRunId(run.id)
},
})
}
const handleCancelRun = () => {
if (!activeRun || activeRun.status !== 'running') {
return
}
cancelRunMutation.mutate({
jobId: activeRun.jobId,
runId: activeRun.id,
}, {
onSuccess: (run) => {
setSelectedRunId(run.id)
},
})
}
const handleSelectJob = (jobId: number) => {
setSelectedJobId(jobId)
setActiveTab('detail')
}
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col">
<Header>
<Header.BackButton to={`/repos/${repoId}`} />
<div className="min-w-0 flex-1 px-3">
<Header.Title className="truncate">Schedules</Header.Title>
<p className="text-xs text-muted-foreground truncate">{repoName}</p>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="h-6 rounded-full px-2 text-xs">{jobs?.length ?? 0} jobs</Badge>
<Badge variant="outline" className={cn('h-6 rounded-full px-2 text-xs', getJobStatusTone({ enabled: true } as ScheduleJob))}>{enabledCount} enabled</Badge>
<Header.Actions>
<Button onClick={() => { setEditingJob(undefined); setDialogOpen(true) }} size="sm" className="hidden sm:flex">
<Plus className="w-4 h-4 mr-2" />
New Schedule
</Button>
<Button onClick={() => { setEditingJob(undefined); setDialogOpen(true) }} size="sm" className="sm:hidden">
<Plus className="w-4 h-4" />
</Button>
</Header.Actions>
</div>
</Header>
<div className="flex flex-1 min-h-0 flex-col overflow-hidden px-2 md:px-6">
{!hasJobs ? (
<div className="flex min-h-0 flex-1 h-full items-start">
<Card className="max-w-3xl border-dashed border-border/70">
<CardContent className="flex flex-col items-start gap-4 p-8 sm:p-10">
<div className="rounded-full border border-border bg-muted/40 p-3">
<CalendarClock className="h-6 w-6 text-muted-foreground" />
</div>
<div className="space-y-2">
<p className="text-xl font-semibold tracking-tight">No schedules yet</p>
<p className="text-sm text-muted-foreground">Create a schedule for this repo to automate recurring agent work, then inspect runs, logs, and sessions here.</p>
</div>
<Button onClick={() => { setEditingJob(undefined); setDialogOpen(true) }}>
<Plus className="w-4 h-4 mr-2" />
Create First Schedule
</Button>
</CardContent>
</Card>
</div>
) : (
<>
{activeTab === 'jobs' && (
<JobsTab
jobs={jobs ?? []}
selectedJobId={selectedJobId}
onSelectJob={handleSelectJob}
/>
)}
{activeTab === 'detail' && (
<JobDetailTab
selectedJob={selectedJob}
onEdit={(job) => { setEditingJob(job); setDialogOpen(true) }}
onDelete={setDeleteJobId}
onToggleEnabled={handleToggleEnabled}
onRunNow={handleRunNow}
updatePending={updateMutation.isPending}
runPending={runMutation.isPending}
runningRun={Boolean(runningRun)}
isJobFetching={isJobFetching}
/>
)}
{activeTab === 'runs' && (
<RunHistoryTab
repoId={repoId}
selectedJob={selectedJob}
runs={runs}
runsLoading={runsLoading}
selectedRunId={selectedRunId}
onSelectRun={setSelectedRunId}
activeRun={activeRun}
selectedRunLoading={selectedRunLoading}
onCancelRun={handleCancelRun}
cancelRunPending={cancelRunMutation.isPending}
/>
)}
</>
)}
</div>
{hasJobs && (
<div className="flex border-t border-border bg-card/80 backdrop-blur-sm pb-[env(safe-area-inset-bottom)]">
<button
type="button"
className={cn(
'flex-1 flex flex-col items-center gap-1 py-2 text-xs font-medium transition-colors',
activeTab === 'jobs'
? 'bg-primary/10 text-primary'
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
)}
onClick={() => setActiveTab('jobs')}
>
<CalendarClock className="h-5 w-5" />
<span>Jobs</span>
</button>
<button
type="button"
className={cn(
'flex-1 flex flex-col items-center gap-1 py-2 text-xs font-medium transition-colors',
activeTab === 'detail'
? 'bg-primary/10 text-primary'
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
)}
onClick={() => setActiveTab('detail')}
>
<Info className="h-5 w-5" />
<span>Detail</span>
</button>
<button
type="button"
className={cn(
'flex-1 flex flex-col items-center gap-1 py-2 text-xs font-medium transition-colors',
activeTab === 'runs'
? 'bg-primary/10 text-primary'
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
)}
onClick={() => setActiveTab('runs')}
>
<History className="h-5 w-5" />
<span>Run History</span>
</button>
</div>
)}
<ScheduleJobDialog
open={dialogOpen}
onOpenChange={(open) => {
setDialogOpen(open)
if (!open) {
setEditingJob(undefined)
}
}}
job={editingJob}
isSaving={createMutation.isPending || updateMutation.isPending}
onSubmit={editingJob ? handleUpdate : handleCreate}
/>
<DeleteDialog
open={deleteJobId !== null}
onOpenChange={(open) => !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}
/>
</div>
)
}
+7 -7
View File
@@ -57,6 +57,7 @@ export function SessionDetail() {
const navigate = useNavigate();
const repoId = Number(id) || 0;
const { preferences, updateSettings } = useSettings();
const { open: openSettings } = useSettingsDialog();
const messageContainerRef = useRef<HTMLDivElement>(null);
const pageRef = useRef<HTMLDivElement>(null);
const promptInputRef = useRef<PromptInputHandle>(null);
@@ -128,7 +129,6 @@ export function SessionDetail() {
const updateSession = useUpdateSession(opcodeUrl, repoDirectory);
const createSession = useCreateSession(opcodeUrl, repoDirectory);
const isTitleGenerating = useTitleGenerating(sessionId);
const { open: openSettings } = useSettingsDialog();
const { model, modelString } = useModelSelection(opcodeUrl, repoDirectory);
const isEditingMessage = useUIState((state) => state.isEditingMessage);
const { isEnabled: ttsEnabled } = useTTS();
@@ -432,24 +432,24 @@ export function SessionDetail() {
<span className="hidden sm:inline">Settings</span>
</Button>
<Header.MobileDropdown>
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
<FolderOpen className="w-4 h-4 mr-2" /> Files
</DropdownMenuItem>
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
<Brain className="w-4 h-4 mr-2" /> Memory
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
<Plug className="w-4 h-4 mr-2" /> MCP
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setLspDialogOpen(true)}>
<Code className="w-4 h-4 mr-2" /> LSP
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
<FolderOpen className="w-4 h-4 mr-2" /> Files
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
</DropdownMenuItem>
</Header.MobileDropdown>
</Header.Actions>
</Header>