fix(schedules): clean up orphaned schedule records when repo is deleted (#255)

* fix(schedules): clean up orphaned schedule records and add schedule URL state management

* refactor(schedules): consolidate schedule tab state into useScheduleUrlState

* fix(schedules): cascade delete schedule runs/jobs and preserve assistant schedules in orphan cleanup

* refactor(schedules): replace deleteJobsByRepo with prepareRepoDelete, add lightweight ID query, remove dead mock

* refactor(schedules): consolidate PromptTemplateDialog form state into single object
This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-05 18:07:25 -04:00
1 parent 70cb62b77b
commit cc89a524c4
24 files changed
+1938 -327

No files matched your search

+2 -1
View File
@@ -209,7 +209,8 @@ export function updateRepoBranch(db: Database, id: number, branch: string): void
}
export function deleteRepo(db: Database, id: number): void {
db.prepare('DELETE FROM schedule_runs WHERE repo_id = ?').run(id)
db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ?').run(id)
const stmt = db.prepare('DELETE FROM repos WHERE id = ?')
stmt.run(id)
}
+24
View File
@@ -116,6 +116,12 @@ export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJo
return rows.map(rowToScheduleJob)
}
export function listScheduleJobIdsByRepo(db: Database, repoId: number): number[] {
const stmt = db.prepare('SELECT id FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
const rows = stmt.all(repoId) as Array<{ id: number }>
return rows.map((row) => row.id)
}
export function listEnabledScheduleJobs(db: Database): ScheduleJob[] {
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC')
const rows = stmt.all() as ScheduleJobRow[]
@@ -200,11 +206,29 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
}
export function deleteScheduleJob(db: Database, repoId: number, jobId: number): boolean {
db.prepare('DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ?').run(repoId, jobId)
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
const result = stmt.run(repoId, jobId)
return result.changes > 0
}
export function cleanupOrphanedSchedules(db: Database): { orphanedJobs: number; orphanedRuns: number } {
const runStmt = db.prepare(`
DELETE FROM schedule_runs
WHERE (repo_id != ? AND repo_id NOT IN (SELECT id FROM repos))
OR job_id NOT IN (SELECT id FROM schedule_jobs)
`)
const orphanedRuns = runStmt.run(ASSISTANT_REPO_ID).changes
const jobStmt = db.prepare(`
DELETE FROM schedule_jobs
WHERE repo_id != ? AND repo_id NOT IN (SELECT id FROM repos)
`)
const orphanedJobs = jobStmt.run(ASSISTANT_REPO_ID).changes
return { orphanedJobs, orphanedRuns }
}
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
+1
View File
@@ -37,6 +37,7 @@ function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStub
listSchedules: () => [],
updateSchedule: () => {},
deleteSchedule: () => {},
prepareRepoDelete: () => {},
} as any
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient))
return app
+2
View File
@@ -273,6 +273,8 @@ app.get('/', async (c) => {
return c.json({ error: 'Repo not found' }, 404)
}
scheduleService.prepareRepoDelete(id)
await repoService.deleteRepoFiles(database, id)
return c.json({ success: true })
+27
View File
@@ -10,6 +10,7 @@ import {
import { getRepoById } from '../db/queries'
import type { ScheduleJobWithRepo } from '../db/schedules'
import {
cleanupOrphanedSchedules,
createScheduleJob,
createScheduleRun,
deleteScheduleJob,
@@ -19,6 +20,7 @@ import {
listAllScheduleJobsWithRepos,
listAllScheduleRuns,
listEnabledScheduleJobs,
listScheduleJobIdsByRepo,
listScheduleJobsByRepo,
listRunningScheduleRuns,
listScheduleRunsByJob,
@@ -444,6 +446,26 @@ export class ScheduleService {
this.onJobChange?.(null, jobId)
}
prepareRepoDelete(repoId: number): void {
const jobIds = listScheduleJobIdsByRepo(this.db, repoId)
for (const jobId of jobIds) {
this.onJobChange?.(null, jobId)
}
}
/**
* Removes any schedule_jobs and schedule_runs whose repo_id (or job_id for
* runs) no longer exists in the repos / schedule_jobs table. Safe to call
* on every startup — no-op when there are no orphans.
*/
cleanupOrphanedSchedules(): { orphanedJobs: number; orphanedRuns: number } {
const result = cleanupOrphanedSchedules(this.db)
if (result.orphanedJobs > 0 || result.orphanedRuns > 0) {
logger.info(`Cleaned up ${result.orphanedJobs} orphaned schedule job(s) and ${result.orphanedRuns} run(s)`)
}
return result
}
listRuns(repoId: number, jobId: number, limit: number = 20): ScheduleRun[] {
this.assertJob(repoId, jobId)
return listScheduleRunsByJob(this.db, repoId, jobId, limit)
@@ -1120,6 +1142,11 @@ export class ScheduleRunner {
}
})
// Clean up any schedule records whose repo no longer exists. This handles
// leftovers from before foreign-key enforcement was enabled, and guards
// against edge cases where a repo row was removed outside the normal flow.
this.scheduleService.cleanupOrphanedSchedules()
await this.scheduleService.recoverRunningRuns()
this.registerAllEnabledJobs()
}
+18 -5
View File
@@ -258,18 +258,31 @@ describe('Database Queries', () => {
})
describe('deleteRepo', () => {
it('should delete repo by ID', () => {
const stmt = {
it('should delete repo schedules before deleting repo by ID', () => {
const deleteRunsStmt = {
run: vi.fn().mockReturnValue({ changes: 2 })
}
const deleteJobsStmt = {
run: vi.fn().mockReturnValue({ changes: 1 })
}
mockDb.prepare.mockReturnValue(stmt)
const deleteRepoStmt = {
run: vi.fn().mockReturnValue({ changes: 1 })
}
mockDb.prepare
.mockReturnValueOnce(deleteRunsStmt)
.mockReturnValueOnce(deleteJobsStmt)
.mockReturnValueOnce(deleteRepoStmt)
db.deleteRepo(mockDb, 1)
expect(mockDb.prepare).toHaveBeenCalledWith(
expect(mockDb.prepare).toHaveBeenNthCalledWith(1, 'DELETE FROM schedule_runs WHERE repo_id = ?')
expect(deleteRunsStmt.run).toHaveBeenCalledWith(1)
expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
expect(deleteJobsStmt.run).toHaveBeenCalledWith(1)
expect(mockDb.prepare).toHaveBeenNthCalledWith(3,
'DELETE FROM repos WHERE id = ?'
)
expect(stmt.run).toHaveBeenCalledWith(1)
expect(deleteRepoStmt.run).toHaveBeenCalledWith(1)
})
})
@@ -3,6 +3,7 @@ import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import {
cleanupOrphanedSchedules,
listAllScheduleJobsWithRepos,
listAllScheduleRuns,
} from '../../src/db/schedules'
@@ -101,4 +102,14 @@ describe('assistant repo (repo_id=0) in global aggregate queries', () => {
expect(run.repoName).toBe('Assistant')
expect(run.repoPath).toBe('assistant')
})
it('cleanupOrphanedSchedules keeps assistant schedules while deleting real repo orphans', () => {
db.exec('DELETE FROM repos WHERE id = 1')
const result = cleanupOrphanedSchedules(db)
expect(result).toEqual({ orphanedJobs: 1, orphanedRuns: 1 })
expect(listAllScheduleJobsWithRepos(db).map((job) => job.repoId)).toEqual([0])
expect(listAllScheduleRuns(db, {}).map((run) => run.repoId)).toEqual([0])
})
})
+34
View File
@@ -72,6 +72,19 @@ describe('schedule database queries', () => {
})
})
it('lists schedule job ids without loading full job rows', () => {
const stmt = {
all: vi.fn().mockReturnValue([{ id: 7 }, { id: 8 }]),
}
mockDb.prepare.mockReturnValue(stmt)
const jobIds = schedulesDb.listScheduleJobIdsByRepo(mockDb, 42)
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT id FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
expect(stmt.all).toHaveBeenCalledWith(42)
expect(jobIds).toEqual([7, 8])
})
it('creates a schedule job and reloads the inserted row', () => {
const insertStmt = {
run: vi.fn().mockReturnValue({ lastInsertRowid: 7 }),
@@ -173,6 +186,27 @@ describe('schedule database queries', () => {
})
})
it('deletes schedule runs before deleting a schedule job', () => {
const deleteRunsStmt = {
run: vi.fn().mockReturnValue({ changes: 2 }),
}
const deleteJobStmt = {
run: vi.fn().mockReturnValue({ changes: 1 }),
}
mockDb.prepare
.mockReturnValueOnce(deleteRunsStmt)
.mockReturnValueOnce(deleteJobStmt)
const deleted = schedulesDb.deleteScheduleJob(mockDb, 42, 7)
expect(mockDb.prepare).toHaveBeenNthCalledWith(1, 'DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ?')
expect(deleteRunsStmt.run).toHaveBeenCalledWith(42, 7)
expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
expect(deleteJobStmt.run).toHaveBeenCalledWith(42, 7)
expect(deleted).toBe(true)
})
it('returns null when updating metadata for a missing run', () => {
const selectStmt = {
get: vi.fn().mockReturnValue(undefined),
+19
View File
@@ -6,11 +6,13 @@ const mocks = vi.hoisted(() => ({
createScheduleJob: vi.fn(),
createScheduleRun: vi.fn(),
deleteScheduleJob: vi.fn(),
cleanupOrphanedSchedules: vi.fn(),
getScheduleJobById: vi.fn(),
getRunningScheduleRunByJob: vi.fn(),
getScheduleRunById: vi.fn(),
listEnabledScheduleJobs: vi.fn(),
listRunningScheduleRuns: vi.fn(),
listScheduleJobIdsByRepo: vi.fn(),
listScheduleJobsByRepo: vi.fn(),
listScheduleRunsByJob: vi.fn(),
updateScheduleJob: vi.fn(),
@@ -35,11 +37,13 @@ vi.mock('../../src/db/schedules', () => ({
createScheduleJob: mocks.createScheduleJob,
createScheduleRun: mocks.createScheduleRun,
deleteScheduleJob: mocks.deleteScheduleJob,
cleanupOrphanedSchedules: mocks.cleanupOrphanedSchedules,
getScheduleJobById: mocks.getScheduleJobById,
getRunningScheduleRunByJob: mocks.getRunningScheduleRunByJob,
getScheduleRunById: mocks.getScheduleRunById,
listEnabledScheduleJobs: mocks.listEnabledScheduleJobs,
listRunningScheduleRuns: mocks.listRunningScheduleRuns,
listScheduleJobIdsByRepo: mocks.listScheduleJobIdsByRepo,
listScheduleJobsByRepo: mocks.listScheduleJobsByRepo,
listScheduleRunsByJob: mocks.listScheduleRunsByJob,
updateScheduleJob: mocks.updateScheduleJob,
@@ -724,6 +728,20 @@ describe('ScheduleService', () => {
expect(() => service.getRun(42, 7, 5)).toThrow('Run not found')
})
it('prepares repo deletion by unregistering repo jobs without deleting records', () => {
const service = new ScheduleService({} as never, createOpenCodeClientStub())
const onJobChange = vi.fn()
service.setJobChangeHandler(onJobChange)
mocks.listScheduleJobIdsByRepo.mockReturnValue([7, 8])
service.prepareRepoDelete(42)
expect(mocks.listScheduleJobIdsByRepo).toHaveBeenCalledWith(expect.anything(), 42)
expect(onJobChange).toHaveBeenCalledWith(null, 7)
expect(onJobChange).toHaveBeenCalledWith(null, 8)
expect(onJobChange).toHaveBeenCalledTimes(2)
})
it('cancels by finalizing the run when the assistant already completed', async () => {
const service = new ScheduleService({} as never, createOpenCodeClientStub())
const runningRun: ScheduleRun = {
@@ -998,6 +1016,7 @@ describe('ScheduleRunner', () => {
beforeEach(() => {
mockCronInstances.length = 0
mockCronStop.mockClear()
mocks.cleanupOrphanedSchedules.mockReturnValue({ orphanedJobs: 0, orphanedRuns: 0 })
})
it('recovers running runs and registers all enabled jobs on start', async () => {
@@ -3,7 +3,8 @@ import { useLocation, useNavigate } from 'react-router-dom'
import { FolderGit2, FolderOpen, CalendarClock, Menu, Info, History, Bot } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useMobile } from '@/hooks/useMobile'
import { useMobileTabBar, useScheduleTab, type ScheduleTabKey } from '@/hooks/useMobileTabBar'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { useScheduleUrlState, type ScheduleTab } from '@/hooks/useScheduleUrlState'
import { useUIState } from '@/stores/uiStateStore'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
@@ -124,7 +125,7 @@ function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, i
]
}
function buildScheduleTabs(scheduleTab: ScheduleTabKey, setScheduleTab: (tab: ScheduleTabKey) => void): TabDef[] {
function buildScheduleTabs(scheduleTab: ScheduleTab, setScheduleTab: (tab: ScheduleTab) => void): TabDef[] {
return [
{
key: 'jobs',
@@ -189,7 +190,7 @@ export const MobileTabBar = memo(function MobileTabBar() {
const { pathname, search } = useLocation()
const navigate = useNavigate()
const { openSheet, open, close } = useMobileTabBar()
const { scheduleTab, setScheduleTab } = useScheduleTab()
const { scheduleTab, setScheduleTab } = useScheduleUrlState()
const isMobile = useMobile()
const isMoreDrawerOpen = useUIState((state) => state.isMoreDrawerOpen)
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
+79 -50
View File
@@ -17,6 +17,77 @@ type PromptTabProps = {
onNewTemplate: () => void
}
type PromptTemplateCardProps = {
template: PromptTemplate
selected?: boolean
onApply?: (template: PromptTemplate) => void
onEdit: (template: PromptTemplate) => void
onDelete: (templateId: number) => void
}
export function PromptTemplateCard({ template, selected = false, onApply, onEdit, onDelete }: PromptTemplateCardProps) {
const cardClassName = `w-full rounded-xl border-2 p-4 text-left transition-all ${
selected
? 'border-primary bg-primary/10 ring-2 ring-primary/30'
: 'border-border bg-card hover:bg-accent/40'
}`
const content = (
<>
<div className="flex flex-wrap items-center gap-2">
<Badge className="border-transparent bg-orange-500 text-[10px] uppercase tracking-wide text-white">
{template.category}
</Badge>
<Badge className="border-transparent bg-slate-600 text-[10px] uppercase tracking-wide 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 line-clamp-3 text-xs text-muted-foreground">{template.suggestedDescription}</p>
{selected && (
<div className="absolute right-2 top-2 flex h-5 w-5 items-center justify-center rounded-full bg-primary">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</>
)
return (
<div className="group relative">
{onApply ? (
<button type="button" onClick={() => onApply(template)} className={cardClassName}>
{content}
</button>
) : (
<div className={cardClassName}>{content}</div>
)}
<div className={`absolute top-2 flex gap-1 transition-opacity ${selected || onApply ? 'right-10' : 'right-2'} ${selected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}>
<Button
type="button"
variant="ghost"
size="icon"
className="h-6 w-6"
onClick={(e) => { e.stopPropagation(); onEdit(template) }}
>
<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(); onDelete(template.id) }}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
)
}
export function PromptTab({
prompt,
onPromptChange,
@@ -50,56 +121,14 @@ export function PromptTab({
const isSelected = selectedPromptTemplateId === template.id
return (
<div key={template.id} className="relative group">
<button
type="button"
onClick={() => onApplyTemplate(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(); onEditTemplate(template) }}
>
<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(); onDeleteTemplate(template.id) }}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
<PromptTemplateCard
key={template.id}
template={template}
selected={isSelected}
onApply={onApplyTemplate}
onEdit={onEditTemplate}
onDelete={onDeleteTemplate}
/>
)
})}
</div>
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react'
import { useState, useEffect, useCallback } 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'
@@ -8,54 +8,61 @@ import { Label } from '@/components/ui/label'
import { Loader2 } from 'lucide-react'
import { useCreatePromptTemplate, useUpdatePromptTemplate } from '@/hooks/usePromptTemplates'
type FormData = Pick<CreatePromptTemplateRequest, 'title' | 'category' | 'cadenceHint' | 'suggestedName' | 'suggestedDescription' | 'description' | 'prompt'>
const INITIAL_FORM: FormData = {
title: '',
category: '',
cadenceHint: '',
suggestedName: '',
suggestedDescription: '',
description: '',
prompt: '',
}
interface PromptTemplateDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
template?: PromptTemplate
initialValues?: Partial<CreatePromptTemplateRequest>
}
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('')
function pickFormData(template?: PromptTemplate, initialValues?: Partial<CreatePromptTemplateRequest>): FormData {
return {
title: template?.title ?? initialValues?.title ?? '',
category: template?.category ?? initialValues?.category ?? '',
cadenceHint: template?.cadenceHint ?? initialValues?.cadenceHint ?? '',
suggestedName: template?.suggestedName ?? initialValues?.suggestedName ?? '',
suggestedDescription: template?.suggestedDescription ?? initialValues?.suggestedDescription ?? '',
description: template?.description ?? initialValues?.description ?? '',
prompt: template?.prompt ?? initialValues?.prompt ?? '',
}
}
export function PromptTemplateDialog({ open, onOpenChange, template, initialValues }: PromptTemplateDialogProps) {
const [form, setForm] = useState<FormData>(INITIAL_FORM)
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])
setForm(open ? pickFormData(template, initialValues) : INITIAL_FORM)
}, [template, open, initialValues])
const handleChange = useCallback((field: keyof FormData) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setForm((prev) => ({ ...prev, [field]: e.target.value }))
}, [])
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(),
title: form.title.trim(),
category: form.category.trim(),
cadenceHint: form.cadenceHint.trim(),
suggestedName: form.suggestedName.trim(),
suggestedDescription: form.suggestedDescription.trim(),
description: form.description.trim(),
prompt: form.prompt.trim(),
}
if (template) {
@@ -65,7 +72,7 @@ export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTem
}
}
const isValid = title.trim() && category.trim() && cadenceHint.trim() && suggestedName.trim() && prompt.trim()
const isValid = form.title.trim() && form.category.trim() && form.cadenceHint.trim() && form.suggestedName.trim() && form.prompt.trim()
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -77,34 +84,34 @@ export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTem
<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" />
<Input id="template-title" value={form.title} onChange={handleChange('title')} 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" />
<Input id="template-category" value={form.category} onChange={handleChange('category')} 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" />
<Input id="template-cadence" value={form.cadenceHint} onChange={handleChange('cadenceHint')} 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" />
<Input id="template-suggested-name" value={form.suggestedName} onChange={handleChange('suggestedName')} 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" />
<Input id="template-description" value={form.description} onChange={handleChange('description')} 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" />
<Input id="template-suggested-description" value={form.suggestedDescription} onChange={handleChange('suggestedDescription')} 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." />
<Textarea id="template-prompt" value={form.prompt} onChange={handleChange('prompt')} 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">
@@ -0,0 +1,162 @@
import { useState, useRef } from 'react'
import type { CreatePromptTemplateRequest } from '@opencode-manager/shared/types'
import type { PromptDialog } from '@/hooks/useScheduleUrlState'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Loader2, FileText, Plus, Upload } from 'lucide-react'
import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates'
import { parseMarkdownTemplate } from '@/lib/schedules/markdownTemplate'
import { PromptTemplateDialog } from './PromptTemplateDialog'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { PromptTemplateCard } from './PromptTab'
interface PromptsTabProps {
promptDialog: PromptDialog
templateId: number | null
onNew: () => void
onEdit: (id: number) => void
onDelete: (id: number) => void
onImport: () => void
onCloseDialog: () => void
}
export function PromptsTab({ promptDialog, templateId, onNew, onEdit, onDelete, onImport, onCloseDialog }: PromptsTabProps) {
const [importValues, setImportValues] = useState<Partial<CreatePromptTemplateRequest> | undefined>()
const fileInputRef = useRef<HTMLInputElement>(null)
const { data: templates = [], isLoading } = usePromptTemplates()
const deleteMutation = useDeletePromptTemplate()
const editingTemplate = templates.find((t) => t.id === templateId)
const dialogOpen = promptDialog === 'new' || promptDialog === 'edit' || promptDialog === 'import'
const deleteDialogOpen = promptDialog === 'delete'
const handleFileImport = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
const content = e.target?.result as string
setImportValues(parseMarkdownTemplate(content, file.name))
onImport()
}
reader.readAsText(file)
event.target.value = ''
}
const handleDialogOpenChange = (open: boolean) => {
if (!open) {
onCloseDialog()
setImportValues(undefined)
}
}
const handleDeleteConfirm = () => {
if (templateId !== null) {
deleteMutation.mutate(templateId, { onSuccess: onCloseDialog })
}
}
const handleDeleteDialogOpenChange = (open: boolean) => {
if (!open && !deleteMutation.isPending) {
onCloseDialog()
}
}
const handleDeleteCancel = () => {
if (!deleteMutation.isPending) {
onCloseDialog()
}
}
return (
<div className="flex h-full flex-col overflow-hidden">
<div className="flex items-center justify-between gap-2 border-b border-border px-4 py-3">
<h2 className="text-sm font-semibold">Prompt templates</h2>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
className="h-7 gap-1 text-xs"
onClick={onNew}
>
<Plus className="h-3 w-3" />
New
</Button>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 gap-1 text-xs"
onClick={() => fileInputRef.current?.click()}
>
<Upload className="h-3 w-3" />
Import .md
</Button>
</div>
</div>
<input
ref={fileInputRef}
type="file"
accept=".md,.markdown,text/markdown"
className="hidden"
onChange={handleFileImport}
/>
<div className="flex-1 overflow-y-auto p-4">
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : templates.length === 0 ? (
<div className="flex min-h-full items-center justify-center">
<Card className="max-w-md border-dashed border-border/70">
<CardContent className="flex flex-col items-center gap-4 p-8 text-center">
<div className="rounded-full border border-border bg-muted/40 p-4">
<FileText className="h-8 w-8 text-muted-foreground" />
</div>
<div className="space-y-2">
<p className="text-lg font-semibold">No templates yet</p>
<p className="text-sm text-muted-foreground">
Create prompt templates to reuse across your schedules.
</p>
</div>
</CardContent>
</Card>
</div>
) : (
<div className="grid gap-3 lg:grid-cols-2">
{templates.map((template) => (
<PromptTemplateCard
key={template.id}
template={template}
onEdit={(item) => onEdit(item.id)}
onDelete={onDelete}
/>
))}
</div>
)}
</div>
<PromptTemplateDialog
open={dialogOpen}
onOpenChange={handleDialogOpenChange}
template={promptDialog === 'edit' ? editingTemplate : undefined}
initialValues={promptDialog === 'import' ? importValues : undefined}
/>
<DeleteDialog
open={deleteDialogOpen}
onOpenChange={handleDeleteDialogOpenChange}
onConfirm={handleDeleteConfirm}
onCancel={handleDeleteCancel}
title="Delete template"
description="Are you sure you want to delete this template?"
isDeleting={deleteMutation.isPending}
/>
</div>
)
}
@@ -0,0 +1,196 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptsTab } from '../PromptsTab'
import type { PromptDialog } from '@/hooks/useScheduleUrlState'
const sampleTemplate = {
id: 1,
title: 'Weekly Health Report',
category: 'Health',
cadenceHint: 'Weekly',
suggestedName: 'weekly-health',
suggestedDescription: 'Runs a weekly health check',
description: 'A weekly health report template',
prompt: 'Run a health check on the repository',
createdAt: 1_000_000,
updatedAt: 1_000_000,
}
const mocks = vi.hoisted(() => ({
deleteMutate: vi.fn(),
}))
vi.mock('@/hooks/usePromptTemplates', () => ({
usePromptTemplates: () => ({ data: [sampleTemplate], isLoading: false }),
useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
useDeletePromptTemplate: () => ({ mutate: mocks.deleteMutate, isPending: false }),
}))
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
interface PromptsTabProps {
promptDialog: PromptDialog
templateId: number | null
onNew: () => void
onEdit: (id: number) => void
onDelete: (id: number) => void
onImport: () => void
onCloseDialog: () => void
}
function createProps(overrides: Partial<PromptsTabProps> = {}): PromptsTabProps {
return {
promptDialog: null,
templateId: null,
onNew: vi.fn(),
onEdit: vi.fn(),
onDelete: vi.fn(),
onImport: vi.fn(),
onCloseDialog: vi.fn(),
...overrides,
}
}
describe('PromptsTab', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('renders the sample template title', () => {
render(<PromptsTab {...createProps()} />, { wrapper: createWrapper() })
expect(screen.getByText('Weekly Health Report')).toBeInTheDocument()
})
it('calls onNew when the New button is clicked', async () => {
const user = userEvent.setup()
const onNew = vi.fn()
render(<PromptsTab {...createProps({ onNew })} />, { wrapper: createWrapper() })
await user.click(screen.getByRole('button', { name: 'New' }))
expect(onNew).toHaveBeenCalledTimes(1)
})
it('calls onDelete when the delete button on a template card is clicked', async () => {
const user = userEvent.setup()
const onDelete = vi.fn()
const { container } = render(<PromptsTab {...createProps({ onDelete })} />, {
wrapper: createWrapper(),
})
const deleteButton = container.querySelector('.lucide-trash2')?.closest('button')
expect(deleteButton).toBeTruthy()
await user.click(deleteButton!)
expect(onDelete).toHaveBeenCalledWith(sampleTemplate.id)
})
it('calls deleteMutate when confirming the delete dialog', async () => {
const user = userEvent.setup()
render(
<PromptsTab {...createProps({ promptDialog: 'delete', templateId: sampleTemplate.id })} />,
{ wrapper: createWrapper() },
)
await waitFor(() => {
expect(screen.getByText('Delete template')).toBeInTheDocument()
})
await user.click(screen.getByRole('button', { name: 'Delete' }))
expect(mocks.deleteMutate).toHaveBeenCalledWith(sampleTemplate.id, expect.any(Object))
})
it('calls onEdit when the edit button on a template card is clicked', async () => {
const user = userEvent.setup()
const onEdit = vi.fn()
const { container } = render(<PromptsTab {...createProps({ onEdit })} />, {
wrapper: createWrapper(),
})
const editButton = container.querySelector('.lucide-pencil')?.closest('button')
expect(editButton).toBeTruthy()
await user.click(editButton!)
expect(onEdit).toHaveBeenCalledWith(sampleTemplate.id)
})
it('shows the edit dialog populated with template values', async () => {
render(
<PromptsTab
{...createProps({ promptDialog: 'edit', templateId: sampleTemplate.id })}
/>,
{ wrapper: createWrapper() },
)
await waitFor(() => {
expect(screen.getByText('Edit template')).toBeInTheDocument()
})
const promptTextarea = screen.getByRole('textbox', { name: 'Prompt' })
expect(promptTextarea).toHaveValue(sampleTemplate.prompt)
})
it('imports a markdown file and shows parsed values in the dialog', async () => {
const user = userEvent.setup()
const fileContent = '---\ntitle: Imported\n---\nHello prompt'
const mockFileReader = {
onload: null as ((e: { target: { result: string } }) => void) | null,
readAsText: vi.fn(function (this: typeof mockFileReader, _file: Blob) {
if (this.onload) {
this.onload({ target: { result: fileContent } })
}
}),
}
vi.stubGlobal('FileReader', vi.fn(() => mockFileReader))
const onImport = vi.fn()
const { container, rerender } = render(
<PromptsTab {...createProps({ onImport })} />,
{ wrapper: createWrapper() },
)
const fileInput = container.querySelector('input[type="file"]')!
const file = new File([fileContent], 'template.md', { type: 'text/markdown' })
await user.upload(fileInput, file)
await waitFor(() => {
expect(onImport).toHaveBeenCalledTimes(1)
})
rerender(
<PromptsTab
promptDialog="import"
templateId={null}
onNew={vi.fn()}
onEdit={vi.fn()}
onDelete={vi.fn()}
onImport={onImport}
onCloseDialog={vi.fn()}
/>,
)
await waitFor(() => {
expect(screen.getByText('New template')).toBeInTheDocument()
})
const promptTextarea = screen.getByRole('textbox', { name: 'Prompt' })
expect(promptTextarea).toHaveValue('Hello prompt')
})
})
@@ -6,3 +6,4 @@ export { RunDetailPanel } from './RunDetailPanel'
export { ScheduleJobDialog } from './ScheduleJobDialog'
export { ScheduleRunMarkdown } from './ScheduleRunMarkdown'
export { ScheduleTabMenu } from './ScheduleTabMenu'
export { PromptsTab } from './PromptsTab'
@@ -0,0 +1,376 @@
import { useEffect } from 'react'
import { renderHook, act } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { describe, it, expect } from 'vitest'
import { useScheduleUrlState } from '../useScheduleUrlState'
/**
* Captures the current location.search into a ref for test assertions.
* Must be rendered inside a <MemoryRouter>.
*/
function LocationCatcher({ capturedSearch }: { capturedSearch: { current: string } }) {
const location = useLocation()
useEffect(() => {
capturedSearch.current = location.search
})
return null
}
/**
* Creates a wrapper that captures the current location.search into a ref
* so tests can verify URL param changes after actions.
*/
function createWrapper(initialEntries: string[], capturedSearch: { current: string }) {
return function Wrapper({ children }: { children: React.ReactNode }) {
return (
<MemoryRouter initialEntries={initialEntries}>
<LocationCatcher capturedSearch={capturedSearch} />
{children}
</MemoryRouter>
)
}
}
function renderScheduleUrlState(initialEntries = ['/']) {
const capturedSearch: { current: string } = { current: '' }
const wrapper = createWrapper(initialEntries, capturedSearch)
const rendered = renderHook(() => useScheduleUrlState(), { wrapper })
return { ...rendered, capturedSearch }
}
describe('useScheduleUrlState', () => {
it('defaults to jobs tab, null dialog, and null ids when URL is empty', () => {
const { result } = renderScheduleUrlState()
expect(result.current.scheduleTab).toBe('jobs')
expect(result.current.dialog).toBeNull()
expect(result.current.jobId).toBeNull()
expect(result.current.runId).toBeNull()
expect(result.current.templateId).toBeNull()
})
it('setScheduleTab updates tab and removes param when set to jobs', () => {
const { result } = renderScheduleUrlState()
act(() => {
result.current.setScheduleTab('prompts')
})
expect(result.current.scheduleTab).toBe('prompts')
act(() => {
result.current.setScheduleTab('jobs')
})
expect(result.current.scheduleTab).toBe('jobs')
})
it('openEditJob sets dialog to edit and sets jobId', () => {
const { result, capturedSearch } = renderScheduleUrlState()
act(() => {
result.current.openEditJob(12)
})
expect(result.current.dialog).toBe('edit')
expect(result.current.jobId).toBe(12)
expect(result.current.templateId).toBeNull()
expect(capturedSearch.current).toContain('scheduleDialog=edit')
expect(capturedSearch.current).toContain('jobId=12')
})
it('openDeleteTemplate sets promptDialog to delete and sets templateId', () => {
const { result } = renderScheduleUrlState()
act(() => {
result.current.openDeleteTemplate(5)
})
expect(result.current.promptDialog).toBe('delete')
expect(result.current.templateId).toBe(5)
expect(result.current.jobId).toBeNull()
})
it('openImportTemplate sets promptDialog to import and clears templateId', () => {
const { result } = renderScheduleUrlState(['/?templateId=3&jobId=7'])
act(() => {
result.current.openImportTemplate()
})
expect(result.current.promptDialog).toBe('import')
expect(result.current.templateId).toBeNull()
expect(result.current.jobId).toBeNull()
})
it('closeDialog after edit preserves scheduleDialog and jobId', () => {
const { result, capturedSearch } = renderScheduleUrlState()
act(() => {
result.current.openEditJob(12)
})
expect(result.current.dialog).toBe('edit')
expect(result.current.jobId).toBe(12)
act(() => {
result.current.closeDialog()
})
expect(result.current.dialog).toBeNull()
expect(result.current.jobId).toBe(12)
expect(result.current.templateId).toBeNull()
expect(capturedSearch.current).not.toContain('scheduleDialog')
expect(capturedSearch.current).toContain('jobId=12')
})
it('closeDialog after delete preserves jobId when canceling', () => {
const { result, capturedSearch } = renderScheduleUrlState()
act(() => {
result.current.openDeleteJob(42)
})
expect(result.current.dialog).toBe('delete')
expect(result.current.jobId).toBe(42)
act(() => {
result.current.closeDialog()
})
expect(result.current.dialog).toBeNull()
expect(result.current.jobId).toBe(42)
expect(capturedSearch.current).not.toContain('scheduleDialog')
expect(capturedSearch.current).toContain('jobId=42')
})
it('closePromptDialog after openNewTemplate clears promptDialog and templateId', () => {
const { result } = renderScheduleUrlState()
// Open new template
act(() => {
result.current.openNewTemplate()
})
expect(result.current.promptDialog).toBe('new')
expect(result.current.templateId).toBeNull()
// Close prompt dialog
act(() => {
result.current.closePromptDialog()
})
expect(result.current.promptDialog).toBeNull()
expect(result.current.templateId).toBeNull()
})
it('parses jobId=abc as null (NaN) and runId=44 as 44', () => {
const { result } = renderScheduleUrlState(['/?jobId=abc&runId=44'])
expect(result.current.jobId).toBeNull()
expect(result.current.runId).toBe(44)
})
it('preserves unrelated params across setScheduleTab and openEditJob and closeDialog', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?assistant=1'])
// setScheduleTab preserves assistant param
act(() => {
result.current.setScheduleTab('runs')
})
expect(capturedSearch.current).toContain('assistant=1')
expect(capturedSearch.current).toContain('scheduleTab=runs')
// openEditJob preserves assistant param
act(() => {
result.current.openEditJob(3)
})
expect(capturedSearch.current).toContain('assistant=1')
expect(capturedSearch.current).toContain('scheduleDialog=edit')
// closeDialog preserves assistant param
act(() => {
result.current.closeDialog()
})
expect(capturedSearch.current).toContain('assistant=1')
expect(capturedSearch.current).not.toContain('scheduleDialog')
})
it('openNewJob sets dialog to new and clears jobId and templateId', () => {
const { result } = renderScheduleUrlState(['/?templateId=2&jobId=5'])
act(() => {
result.current.openNewJob()
})
expect(result.current.dialog).toBe('new')
expect(result.current.jobId).toBeNull()
expect(result.current.templateId).toBeNull()
})
it('openDeleteJob sets dialog to delete and sets jobId', () => {
const { result } = renderScheduleUrlState()
act(() => {
result.current.openDeleteJob(42)
})
expect(result.current.dialog).toBe('delete')
expect(result.current.jobId).toBe(42)
expect(result.current.templateId).toBeNull()
})
it('openEditTemplate sets promptDialog to edit and sets templateId', () => {
const { result } = renderScheduleUrlState()
act(() => {
result.current.openEditTemplate(99)
})
expect(result.current.promptDialog).toBe('edit')
expect(result.current.templateId).toBe(99)
expect(result.current.jobId).toBeNull()
})
it('selectRun sets and clears runId', () => {
const { result } = renderScheduleUrlState()
act(() => {
result.current.selectRun(20)
})
expect(result.current.runId).toBe(20)
act(() => {
result.current.selectRun(null)
})
expect(result.current.runId).toBeNull()
})
it('reads valid scheduleTab from URL', () => {
const { result } = renderScheduleUrlState(['/?scheduleTab=detail'])
expect(result.current.scheduleTab).toBe('detail')
})
it('reads valid scheduleDialog from URL', () => {
const { result } = renderScheduleUrlState(['/?scheduleDialog=edit'])
expect(result.current.dialog).toBe('edit')
})
it('reads valid promptDialog from URL', () => {
const { result } = renderScheduleUrlState(['/?promptDialog=import'])
expect(result.current.promptDialog).toBe('import')
})
it('resolves invalid tab values to jobs', () => {
const { result } = renderScheduleUrlState(['/?scheduleTab=invalid'])
expect(result.current.scheduleTab).toBe('jobs')
})
it('resolves invalid dialog values to null', () => {
const { result } = renderScheduleUrlState(['/?scheduleDialog=invalid'])
expect(result.current.dialog).toBeNull()
})
it('closeDialog for new dialog does not affect jobId', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?scheduleDialog=new&jobId=7'])
expect(result.current.dialog).toBe('new')
expect(result.current.jobId).toBe(7)
act(() => {
result.current.closeDialog()
})
expect(result.current.dialog).toBeNull()
expect(result.current.jobId).toBe(7)
expect(capturedSearch.current).not.toContain('scheduleDialog')
expect(capturedSearch.current).toContain('jobId=7')
})
it('closePromptDialog for import clears promptDialog but preserves jobId', () => {
const { result } = renderScheduleUrlState(['/?jobId=7&promptDialog=import'])
act(() => {
result.current.closePromptDialog()
})
expect(result.current.promptDialog).toBeNull()
// closePromptDialog does not touch jobId
expect(result.current.jobId).toBe(7)
})
it('returns stable function references across rerenders', () => {
const { result, rerender } = renderScheduleUrlState()
const firstSetScheduleTab = result.current.setScheduleTab
const firstOpenEditJob = result.current.openEditJob
const firstCloseDialog = result.current.closeDialog
const firstClosePromptDialog = result.current.closePromptDialog
const firstSelectJobAndView = result.current.selectJobAndView
const firstSelectJobAndCloseDialog = result.current.selectJobAndCloseDialog
const firstReplaceUrlParams = result.current.replaceUrlParams
rerender()
expect(result.current.setScheduleTab).toBe(firstSetScheduleTab)
expect(result.current.openEditJob).toBe(firstOpenEditJob)
expect(result.current.closeDialog).toBe(firstCloseDialog)
expect(result.current.closePromptDialog).toBe(firstClosePromptDialog)
expect(result.current.selectJobAndView).toBe(firstSelectJobAndView)
expect(result.current.selectJobAndCloseDialog).toBe(firstSelectJobAndCloseDialog)
expect(result.current.replaceUrlParams).toBe(firstReplaceUrlParams)
})
describe('combined atomic URL mutations', () => {
it('selectJobAndView sets jobId and scheduleTab in a single navigation', () => {
const { result, capturedSearch } = renderScheduleUrlState()
act(() => {
result.current.selectJobAndView(42)
})
expect(result.current.jobId).toBe(42)
expect(result.current.scheduleTab).toBe('detail')
expect(capturedSearch.current).toContain('jobId=42')
expect(capturedSearch.current).toContain('scheduleTab=detail')
})
it('selectJobAndView preserves unrelated params', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?assistant=1'])
act(() => {
result.current.selectJobAndView(99)
})
expect(capturedSearch.current).toContain('assistant=1')
expect(capturedSearch.current).toContain('jobId=99')
expect(capturedSearch.current).toContain('scheduleTab=detail')
})
it('selectJobAndCloseDialog sets jobId and removes scheduleDialog', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?scheduleDialog=new'])
act(() => {
result.current.selectJobAndCloseDialog(7)
})
expect(result.current.jobId).toBe(7)
expect(result.current.dialog).toBeNull()
expect(capturedSearch.current).not.toContain('scheduleDialog')
expect(capturedSearch.current).toContain('jobId=7')
})
it('selectJobAndCloseDialog from edit preserves jobId and removes dialog', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?scheduleDialog=edit&jobId=3'])
act(() => {
result.current.selectJobAndCloseDialog(3)
})
expect(result.current.jobId).toBe(3)
expect(result.current.dialog).toBeNull()
expect(capturedSearch.current).not.toContain('scheduleDialog')
expect(capturedSearch.current).toContain('jobId=3')
})
it('selectJobAndCloseDialog preserves unrelated params', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?scheduleDialog=edit&assistant=1'])
act(() => {
result.current.selectJobAndCloseDialog(5)
})
expect(capturedSearch.current).toContain('assistant=1')
expect(capturedSearch.current).not.toContain('scheduleDialog')
expect(capturedSearch.current).toContain('jobId=5')
})
it('replaceUrlParams can set and delete multiple params atomically', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?foo=1&bar=2'])
act(() => {
result.current.replaceUrlParams((p) => {
p.set('jobId', '10')
p.set('scheduleTab', 'runs')
p.delete('foo')
})
})
expect(result.current.jobId).toBe(10)
expect(result.current.scheduleTab).toBe('runs')
expect(capturedSearch.current).toContain('jobId=10')
expect(capturedSearch.current).toContain('scheduleTab=runs')
expect(capturedSearch.current).not.toContain('foo=')
expect(capturedSearch.current).toContain('bar=2')
})
it('replaceUrlParams preserves all params when no modifications are made', () => {
const { result, capturedSearch } = renderScheduleUrlState(['/?jobId=5&scheduleTab=detail'])
act(() => {
result.current.replaceUrlParams((_p) => {
// No modifications
})
})
expect(result.current.jobId).toBe(5)
expect(result.current.scheduleTab).toBe('detail')
expect(capturedSearch.current).toContain('jobId=5')
expect(capturedSearch.current).toContain('scheduleTab=detail')
})
})
})
+1 -79
View File
@@ -1,7 +1,7 @@
import { renderHook, act } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { describe, it, expect } from 'vitest'
import { useMobileTabBar, useScheduleTab, type MobileSheetKey } from './useMobileTabBar'
import { useMobileTabBar, type MobileSheetKey } from './useMobileTabBar'
function renderHookWithRouter<T>(renderFn: () => T) {
const wrapper = ({ children }: { children: React.ReactNode }) => (
@@ -112,81 +112,3 @@ describe('useMobileTabBar', () => {
expect(result.current.open).toBe(firstOpen)
})
})
describe('useScheduleTab', () => {
it('defaults to jobs when no param is set', () => {
const { result } = renderHook(() => useScheduleTab(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/repos/1/schedules']}>{children}</MemoryRouter>
),
})
expect(result.current.scheduleTab).toBe('jobs')
})
it('reads scheduleTab from URL param', () => {
const { result } = renderHook(() => useScheduleTab(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/repos/1/schedules?scheduleTab=runs']}>{children}</MemoryRouter>
),
})
expect(result.current.scheduleTab).toBe('runs')
})
it('setScheduleTab updates the param', () => {
const { result } = renderHook(() => useScheduleTab(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/repos/1/schedules']}>{children}</MemoryRouter>
),
})
act(() => {
result.current.setScheduleTab('detail')
})
expect(result.current.scheduleTab).toBe('detail')
})
it('setScheduleTab(jobs) removes the param', () => {
const { result } = renderHook(() => useScheduleTab(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/repos/1/schedules?scheduleTab=detail']}>{children}</MemoryRouter>
),
})
expect(result.current.scheduleTab).toBe('detail')
act(() => {
result.current.setScheduleTab('jobs')
})
expect(result.current.scheduleTab).toBe('jobs')
})
it('resolves invalid values to jobs', () => {
const { result } = renderHook(() => useScheduleTab(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/repos/1/schedules?scheduleTab=invalid']}>{children}</MemoryRouter>
),
})
expect(result.current.scheduleTab).toBe('jobs')
})
it('returns stable scheduleTab identity across rerenders when search is unchanged', () => {
const { result, rerender } = renderHook(() => useScheduleTab(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/repos/1/schedules?scheduleTab=runs']}>
{children}
</MemoryRouter>
),
})
const firstScheduleTab = result.current.scheduleTab
rerender()
expect(result.current.scheduleTab).toBe(firstScheduleTab)
})
it('setScheduleTab callback maintains stable identity across rerenders', () => {
const { result, rerender } = renderHook(() => useScheduleTab(), {
wrapper: ({ children }) => (
<MemoryRouter initialEntries={['/repos/1/schedules']}>{children}</MemoryRouter>
),
})
const firstSetScheduleTab = result.current.setScheduleTab
rerender()
expect(result.current.setScheduleTab).toBe(firstSetScheduleTab)
})
})
-38
View File
@@ -44,41 +44,3 @@ export function useMobileTabBar(): UseMobileTabBarReturn {
close,
}
}
export type ScheduleTabKey = 'jobs' | 'detail' | 'runs'
export interface UseScheduleTabReturn {
scheduleTab: ScheduleTabKey
setScheduleTab: (tab: ScheduleTabKey) => void
}
export function useScheduleTab(): UseScheduleTabReturn {
const navigate = useNavigate()
const location = useLocation()
const searchRef = useRef(location.search)
useEffect(() => {
searchRef.current = location.search
}, [location.search])
const scheduleTab = useMemo<ScheduleTabKey>(() => {
const searchParams = new URLSearchParams(location.search)
const tabParam = searchParams.get('scheduleTab')
return tabParam === 'detail' || tabParam === 'runs' ? tabParam : 'jobs'
}, [location.search])
const setScheduleTab = useCallback((tab: ScheduleTabKey) => {
const newParams = new URLSearchParams(searchRef.current)
if (tab === 'jobs') {
newParams.delete('scheduleTab')
} else {
newParams.set('scheduleTab', tab)
}
navigate({ search: newParams.toString() }, { replace: true })
}, [navigate])
return {
scheduleTab,
setScheduleTab,
}
}
+207
View File
@@ -0,0 +1,207 @@
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
export type ScheduleTab = 'jobs' | 'detail' | 'runs' | 'prompts'
export type ScheduleDialog = 'new' | 'edit' | 'delete' | null
export type PromptDialog = 'new' | 'edit' | 'delete' | 'import' | null
export interface UseScheduleUrlStateReturn {
scheduleTab: ScheduleTab
setScheduleTab: (t: ScheduleTab) => void
dialog: ScheduleDialog
promptDialog: PromptDialog
jobId: number | null
runId: number | null
templateId: number | null
openNewJob: () => void
openEditJob: (jobId: number) => void
openDeleteJob: (jobId: number) => void
openNewTemplate: () => void
openEditTemplate: (templateId: number) => void
openDeleteTemplate: (templateId: number) => void
openImportTemplate: () => void
closeDialog: () => void
closePromptDialog: () => void
selectRun: (runId: number | null) => void
selectJobAndView: (jobId: number) => void
selectJobAndCloseDialog: (jobId: number) => void
replaceUrlParams: (updater: (params: URLSearchParams) => void) => void
}
function parseNullableInt(value: string | null): number | null {
if (value === null || value === '') return null
const n = Number(value)
return Number.isFinite(n) ? n : null
}
export function useScheduleUrlState(): UseScheduleUrlStateReturn {
const navigate = useNavigate()
const location = useLocation()
const searchRef = useRef(location.search)
useEffect(() => {
searchRef.current = location.search
}, [location.search])
const searchParams = useMemo(() => new URLSearchParams(location.search), [location.search])
const scheduleTab = useMemo<ScheduleTab>(() => {
const tabParam = searchParams.get('scheduleTab')
if (tabParam === 'detail' || tabParam === 'runs' || tabParam === 'prompts') {
return tabParam
}
return 'jobs'
}, [searchParams])
const dialog = useMemo<ScheduleDialog>(() => {
const d = searchParams.get('scheduleDialog')
if (d === 'new' || d === 'edit' || d === 'delete') {
return d
}
return null
}, [searchParams])
const promptDialog = useMemo<PromptDialog>(() => {
const d = searchParams.get('promptDialog')
if (d === 'new' || d === 'edit' || d === 'delete' || d === 'import') {
return d
}
return null
}, [searchParams])
const jobId = useMemo<number | null>(() => parseNullableInt(searchParams.get('jobId')), [searchParams])
const runId = useMemo<number | null>(() => parseNullableInt(searchParams.get('runId')), [searchParams])
const templateId = useMemo<number | null>(() => parseNullableInt(searchParams.get('templateId')), [searchParams])
const replaceUrlParams = useCallback((updater: (params: URLSearchParams) => void) => {
const p = new URLSearchParams(searchRef.current)
updater(p)
navigate({ search: p.toString() }, { replace: true })
}, [navigate])
const setScheduleTab = useCallback((tab: ScheduleTab) => {
replaceUrlParams((p) => {
if (tab === 'jobs') {
p.delete('scheduleTab')
} else {
p.set('scheduleTab', tab)
}
})
}, [replaceUrlParams])
const openNewJob = useCallback(() => {
replaceUrlParams((p) => {
p.set('scheduleDialog', 'new')
p.delete('jobId')
p.delete('templateId')
})
}, [replaceUrlParams])
const openEditJob = useCallback((id: number) => {
replaceUrlParams((p) => {
p.set('scheduleDialog', 'edit')
p.set('jobId', String(id))
p.delete('templateId')
})
}, [replaceUrlParams])
const openDeleteJob = useCallback((id: number) => {
replaceUrlParams((p) => {
p.set('scheduleDialog', 'delete')
p.set('jobId', String(id))
p.delete('templateId')
})
}, [replaceUrlParams])
const openNewTemplate = useCallback(() => {
replaceUrlParams((p) => {
p.set('promptDialog', 'new')
p.delete('templateId')
p.delete('jobId')
})
}, [replaceUrlParams])
const openEditTemplate = useCallback((id: number) => {
replaceUrlParams((p) => {
p.set('promptDialog', 'edit')
p.set('templateId', String(id))
p.delete('jobId')
})
}, [replaceUrlParams])
const openDeleteTemplate = useCallback((id: number) => {
replaceUrlParams((p) => {
p.set('promptDialog', 'delete')
p.set('templateId', String(id))
p.delete('jobId')
})
}, [replaceUrlParams])
const openImportTemplate = useCallback(() => {
replaceUrlParams((p) => {
p.set('promptDialog', 'import')
p.delete('templateId')
p.delete('jobId')
})
}, [replaceUrlParams])
const closeDialog = useCallback(() => {
replaceUrlParams((p) => {
p.delete('scheduleDialog')
})
}, [replaceUrlParams])
const closePromptDialog = useCallback(() => {
replaceUrlParams((p) => {
p.delete('promptDialog')
p.delete('templateId')
})
}, [replaceUrlParams])
const selectRun = useCallback((id: number | null) => {
replaceUrlParams((p) => {
if (id === null) {
p.delete('runId')
} else {
p.set('runId', String(id))
}
})
}, [replaceUrlParams])
const selectJobAndView = useCallback((id: number) => {
replaceUrlParams((p) => {
p.set('jobId', String(id))
p.set('scheduleTab', 'detail')
})
}, [replaceUrlParams])
const selectJobAndCloseDialog = useCallback((id: number) => {
replaceUrlParams((p) => {
p.delete('scheduleDialog')
p.set('jobId', String(id))
})
}, [replaceUrlParams])
return {
scheduleTab,
setScheduleTab,
dialog,
promptDialog,
jobId,
runId,
templateId,
openNewJob,
openEditJob,
openDeleteJob,
openNewTemplate,
openEditTemplate,
openDeleteTemplate,
openImportTemplate,
closeDialog,
closePromptDialog,
selectRun,
selectJobAndView,
selectJobAndCloseDialog,
replaceUrlParams,
}
}
@@ -0,0 +1,221 @@
import { describe, it, expect } from 'vitest'
import { parseMarkdownTemplate } from '../markdownTemplate'
describe('parseMarkdownTemplate', () => {
describe('frontmatter', () => {
it('parses all keys from frontmatter', () => {
const raw = `---
title: My Template
category: Health
cadenceHint: Weekly
suggestedName: My Suggested Name
suggestedDescription: A suggested description
description: A short description
---
This is the prompt body`
const result = parseMarkdownTemplate(raw)
expect(result).toEqual({
title: 'My Template',
category: 'Health',
cadenceHint: 'Weekly',
suggestedName: 'My Suggested Name',
suggestedDescription: 'A suggested description',
description: 'A short description',
prompt: 'This is the prompt body',
})
})
it('strips surrounding double quotes from values', () => {
const raw = '---\ntitle: "My Template"\ncategory: \'Health\'\n---\nBody'
const result = parseMarkdownTemplate(raw)
expect(result.title).toBe('My Template')
expect(result.category).toBe('Health')
})
it('maps cadence alias to cadenceHint', () => {
const raw = '---\ncadence: Daily\n---\nBody'
const result = parseMarkdownTemplate(raw)
expect(result.cadenceHint).toBe('Daily')
})
it('ignores unknown frontmatter keys', () => {
const raw = '---\ntitle: Known\nunknownKey: should be ignored\nfoo: bar\n---\nBody'
const result = parseMarkdownTemplate(raw)
expect(result.title).toBe('Known')
expect(result).not.toHaveProperty('unknownKey')
expect(result).not.toHaveProperty('foo')
})
it('does not throw on malformed frontmatter (no closing ---)', () => {
const raw = '---\ntitle: broken\nno closing delimiter\n\nBody text'
const result = parseMarkdownTemplate(raw)
expect(result.title).toBe('Imported template')
expect(result.prompt).toBe(raw.trim())
})
it('does not throw on empty frontmatter block', () => {
const raw = '---\n---\n# Title from H1\n\nBody'
const result = parseMarkdownTemplate(raw)
expect(result.title).toBe('Title from H1')
expect(result.prompt).toBe('# Title from H1\n\nBody')
})
it('handles frontmatter with only some keys present', () => {
const raw = '---\ntitle: Partial\ncategory: Test\n---\nBody'
const result = parseMarkdownTemplate(raw)
expect(result.title).toBe('Partial')
expect(result.category).toBe('Test')
expect(result.cadenceHint).toBeUndefined()
expect(result.suggestedName).toBe('Partial')
expect(result.prompt).toBe('Body')
})
})
describe('title derivation', () => {
it('derives title from first H1 when no frontmatter title', () => {
const raw = '# My Heading\n\nSome prompt body'
const result = parseMarkdownTemplate(raw)
expect(result.title).toBe('My Heading')
expect(result.prompt).toBe(raw.trim())
})
it('derives title from fileName when no frontmatter title and no H1', () => {
const raw = 'Just some prompt text'
const result = parseMarkdownTemplate(raw, 'weekly-report.md')
expect(result.title).toBe('weekly-report')
expect(result.prompt).toBe(raw.trim())
})
it('derives title from fileName stripping .markdown extension', () => {
const raw = 'Body'
const result = parseMarkdownTemplate(raw, 'My Template.markdown')
expect(result.title).toBe('My Template')
})
it('uses default title when no frontmatter title, no H1, and no fileName', () => {
const raw = 'Some prompt'
const result = parseMarkdownTemplate(raw)
expect(result.title).toBe('Imported template')
})
it('uses default title for empty prompt with no fileName', () => {
const result = parseMarkdownTemplate('')
expect(result.title).toBe('Imported template')
expect(result.prompt).toBe('')
})
})
describe('suggestedName default', () => {
it('defaults suggestedName to title when not provided', () => {
const raw = '---\ntitle: My Title\n---\nBody'
const result = parseMarkdownTemplate(raw)
expect(result.suggestedName).toBe('My Title')
})
it('keeps explicit suggestedName when provided', () => {
const raw = '---\ntitle: My Title\nsuggestedName: Explicit Name\n---\nBody'
const result = parseMarkdownTemplate(raw)
expect(result.suggestedName).toBe('Explicit Name')
})
})
describe('empty and edge cases', () => {
it('returns empty prompt for empty input', () => {
const result = parseMarkdownTemplate('')
expect(result.prompt).toBe('')
expect(result.title).toBe('Imported template')
})
it('handles input with only whitespace', () => {
const result = parseMarkdownTemplate(' \n \n ')
expect(result.prompt).toBe('')
expect(result.title).toBe('Imported template')
})
it('handles CRLF line endings in frontmatter', () => {
const raw = '---\r\ntitle: CRLF Test\r\ncategory: Test\r\n---\r\nBody text'
const result = parseMarkdownTemplate(raw)
expect(result.title).toBe('CRLF Test')
expect(result.category).toBe('Test')
expect(result.prompt).toBe('Body text')
})
})
describe('prompt handling', () => {
it('returns entire content as prompt when no frontmatter', () => {
const raw = '# Title\n\nSome **markdown** content\n\n- list item'
const result = parseMarkdownTemplate(raw)
expect(result.prompt).toBe(raw.trim())
expect(result.title).toBe('Title')
})
it('trims prompt body', () => {
const raw = '---\ntitle: Test\n---\n \n Body with spaces around \n '
const result = parseMarkdownTemplate(raw)
expect(result.prompt).toBe('Body with spaces around')
})
it('prompt is empty string for frontmatter-only input', () => {
const raw = '---\ntitle: Test\n---'
const result = parseMarkdownTemplate(raw)
expect(result.prompt).toBe('')
})
})
describe('no frontmatter at all', () => {
it('parses simple markdown without frontmatter', () => {
const raw = '# Document Title\n\nSome content here'
const result = parseMarkdownTemplate(raw)
expect(result.title).toBe('Document Title')
expect(result.prompt).toBe(raw.trim())
})
it('handles text without any markdown headings', () => {
const raw = 'Just plain text with no heading'
const result = parseMarkdownTemplate(raw, 'my-file.md')
expect(result.title).toBe('my-file')
expect(result.prompt).toBe(raw.trim())
})
})
})
@@ -0,0 +1,116 @@
export interface ParsedMarkdownTemplate {
title?: string
category?: string
cadenceHint?: string
suggestedName?: string
suggestedDescription?: string
description?: string
prompt: string
}
interface FrontmatterMap {
title?: string
category?: string
cadenceHint?: string
suggestedName?: string
suggestedDescription?: string
description?: string
}
const KEY_MAP: Record<string, keyof FrontmatterMap> = {
title: 'title',
category: 'category',
cadenceHint: 'cadenceHint',
cadence: 'cadenceHint',
suggestedName: 'suggestedName',
suggestedDescription: 'suggestedDescription',
description: 'description',
}
function stripQuotes(value: string): string {
const trimmed = value.trim()
if (trimmed.length >= 2) {
const first = trimmed[0]
const last = trimmed[trimmed.length - 1]
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
return trimmed.slice(1, -1)
}
}
return trimmed
}
function parseFrontmatter(raw: string): { frontmatter: FrontmatterMap; body: string } | null {
if (!raw.startsWith('---\n') && !raw.startsWith('---\r\n')) {
return null
}
const closing = raw.indexOf('\n---', 1)
if (closing === -1) {
return null
}
const fmBlock = raw.slice(4, closing)
const body = raw.slice(closing + 5)
const frontmatter: FrontmatterMap = {}
for (const line of fmBlock.split('\n')) {
const colonIndex = line.indexOf(':')
if (colonIndex === -1) continue
const key = line.slice(0, colonIndex).trim()
const value = line.slice(colonIndex + 1).trim()
if (!key || value === undefined) continue
const mappedKey = KEY_MAP[key]
if (mappedKey) {
frontmatter[mappedKey] = stripQuotes(value)
}
}
return { frontmatter, body }
}
function extractFirstH1(text: string): string | undefined {
const match = text.match(/^#\s+(.+)$/m)
return match?.[1]?.trim()
}
function deriveTitle(fileName?: string): string {
if (!fileName) return 'Imported template'
const lower = fileName.toLowerCase()
if (lower.endsWith('.md')) return fileName.slice(0, -3)
if (lower.endsWith('.markdown')) return fileName.slice(0, -9)
return fileName
}
export function parseMarkdownTemplate(raw: string, fileName?: string): ParsedMarkdownTemplate {
const result: ParsedMarkdownTemplate = { prompt: '' }
const parsed = parseFrontmatter(raw)
if (parsed) {
if (parsed.frontmatter.title !== undefined) result.title = parsed.frontmatter.title
if (parsed.frontmatter.category !== undefined) result.category = parsed.frontmatter.category
if (parsed.frontmatter.cadenceHint !== undefined) result.cadenceHint = parsed.frontmatter.cadenceHint
if (parsed.frontmatter.suggestedName !== undefined) result.suggestedName = parsed.frontmatter.suggestedName
if (parsed.frontmatter.suggestedDescription !== undefined) result.suggestedDescription = parsed.frontmatter.suggestedDescription
if (parsed.frontmatter.description !== undefined) result.description = parsed.frontmatter.description
result.prompt = parsed.body.trim()
} else {
result.prompt = raw.trim()
}
if (!result.title && result.prompt) {
result.title = extractFirstH1(result.prompt)
}
if (!result.title) {
result.title = deriveTitle(fileName)
}
if (!result.suggestedName && result.title) {
result.suggestedName = result.title
}
return result
}
+47 -31
View File
@@ -2,7 +2,7 @@ import { useState, useMemo, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAllSchedules, useAllScheduleRuns, useCancelRepoScheduleRun } from '@/hooks/useSchedules'
import { useDeleteRepoSchedule, useRunRepoSchedule, useUpdateRepoSchedule, useCreateRepoSchedule } from '@/hooks/useSchedules'
import { ScheduleJobDialog, RunHistoryCards } from '@/components/schedules'
import { ScheduleJobDialog, RunHistoryCards, PromptsTab } from '@/components/schedules'
import type { CreateScheduleJobRequest } from '@opencode-manager/shared/types'
import { toUpdateScheduleRequest, formatScheduleShortLabel, getJobStatusTone, formatTimestamp } from '@/components/schedules/schedule-utils'
import { Header } from '@/components/ui/header'
@@ -14,6 +14,9 @@ import { DeleteDialog } from '@/components/ui/delete-dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { CalendarClock, Loader2, Plus, ArrowLeft, Play, Pencil, Trash2, Pause, PlayCircle, Clock3, History, SlidersHorizontal } from 'lucide-react'
import { useScheduleUrlState } from '@/hooks/useScheduleUrlState'
import type { ScheduleTab } from '@/hooks/useScheduleUrlState'
import type { ScheduleJobWithRepo, ScheduleRunWithContext } from '@/api/schedules'
import { Combobox } from '@/components/ui/combobox'
import { isAssistantRepoId } from '@/lib/schedules/schedule-target'
@@ -25,24 +28,21 @@ type SortOption = 'nextRun' | 'name' | 'repo'
export function GlobalSchedules() {
const navigate = useNavigate()
const [dialogOpen, setDialogOpen] = useState(false)
const [editingJob, setEditingJob] = useState<ScheduleJobWithRepo | null>(null)
const [deletingJob, setDeletingJob] = useState<ScheduleJobWithRepo | null>(null)
const [selectedRepoId, setSelectedRepoId] = useState<number | undefined>(undefined)
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all')
const [scheduleModeFilter, setScheduleModeFilter] = useState<ScheduleModeFilter>('all')
const [repoFilter, setRepoFilter] = useState<string>('all')
const [sortOption, setSortOption] = useState<SortOption>('nextRun')
const [activeTab, setActiveTab] = useState<'jobs' | 'runs'>('jobs')
const [runStatusFilter, setRunStatusFilter] = useState<string>('all')
const [runRepoFilter, setRunRepoFilter] = useState<string>('all')
const [runTriggerFilter, setRunTriggerFilter] = useState<string>('all')
const [runSortOption, setRunSortOption] = useState<'startedAt' | 'jobName' | 'duration'>('startedAt')
const [runOffset, setRunOffset] = useState(0)
const [allRuns, setAllRuns] = useState<ScheduleRunWithContext[]>([])
const [selectedRunId, setSelectedRunId] = useState<number | null>(null)
const runOffsetRef = useRef(runOffset)
const { scheduleTab, setScheduleTab, dialog, promptDialog, jobId, runId, templateId, openNewJob, openEditJob, openDeleteJob, openNewTemplate, openEditTemplate, openDeleteTemplate, openImportTemplate, closeDialog, closePromptDialog, selectRun } = useScheduleUrlState()
const cancelRunMutation = useCancelRepoScheduleRun()
const cancelRunPending = cancelRunMutation.isPending
@@ -52,6 +52,9 @@ export function GlobalSchedules() {
const { data: jobs = [], isLoading, error } = useAllSchedules()
const editingJob = useMemo(() => dialog === 'edit' ? (jobs.find(j => j.id === jobId) ?? null) : null, [dialog, jobId, jobs])
const deletingJob = useMemo(() => dialog === 'delete' ? (jobs.find(j => j.id === jobId) ?? null) : null, [dialog, jobId, jobs])
const runsParams = useMemo(() => ({
limit: 50,
offset: runOffset,
@@ -60,7 +63,7 @@ export function GlobalSchedules() {
triggerSource: runTriggerFilter !== 'all' ? runTriggerFilter : undefined,
}), [runStatusFilter, runRepoFilter, runTriggerFilter, runOffset])
const { data: runsPage = [], isLoading: runsLoading } = useAllScheduleRuns(runsParams, activeTab === 'runs')
const { data: runsPage = [], isLoading: runsLoading } = useAllScheduleRuns(runsParams, scheduleTab === 'runs')
const createMutation = useCreateRepoSchedule()
const deleteMutation = useDeleteRepoSchedule()
@@ -230,7 +233,7 @@ export function GlobalSchedules() {
deleteMutation.mutate(
{ repoId: deletingJob.repoId, jobId: deletingJob.id },
{ onSuccess: () => setDeletingJob(null) }
{ onSuccess: () => closeDialog() }
)
}
@@ -251,8 +254,7 @@ export function GlobalSchedules() {
}
const handleEdit = (job: ScheduleJobWithRepo) => {
setEditingJob(job)
setDialogOpen(true)
openEditJob(job.id)
}
const handleCreate = (data: CreateScheduleJobRequest) => {
@@ -261,7 +263,7 @@ export function GlobalSchedules() {
{ repoId: selectedRepoId, data },
{
onSuccess: () => {
setDialogOpen(false)
closeDialog()
setSelectedRepoId(undefined)
},
}
@@ -278,8 +280,7 @@ export function GlobalSchedules() {
},
{
onSuccess: () => {
setDialogOpen(false)
setEditingJob(null)
closeDialog()
},
}
)
@@ -331,7 +332,7 @@ export function GlobalSchedules() {
</Badge>
<Header.Actions>
<Button
onClick={() => { setEditingJob(null); setSelectedRepoId(undefined); setDialogOpen(true) }}
onClick={() => { openNewJob(); setSelectedRepoId(undefined) }}
size="sm"
className="hidden sm:flex"
>
@@ -339,7 +340,7 @@ export function GlobalSchedules() {
New Schedule
</Button>
<Button
onClick={() => { setEditingJob(null); setSelectedRepoId(undefined); setDialogOpen(true) }}
onClick={() => { openNewJob(); setSelectedRepoId(undefined) }}
size="sm"
className="sm:hidden h-10 w-10 p-0"
>
@@ -349,7 +350,7 @@ export function GlobalSchedules() {
</div>
</Header>
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'jobs' | 'runs')} className="flex-1 min-h-0 flex flex-col overflow-hidden">
<Tabs value={scheduleTab} onValueChange={(v) => setScheduleTab(v as ScheduleTab)} className="flex-1 min-h-0 flex flex-col overflow-hidden">
<div className="border-b border-border px-4">
<TabsList className="h-auto gap-0 rounded-none border-0 bg-transparent p-0">
<TabsTrigger value="jobs" className="rounded-none border-b-2 border-transparent px-4 py-2.5 text-sm data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">
@@ -358,6 +359,9 @@ export function GlobalSchedules() {
<TabsTrigger value="runs" className="rounded-none border-b-2 border-transparent px-4 py-2.5 text-sm data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">
Run History
</TabsTrigger>
<TabsTrigger value="prompts" className="rounded-none border-b-2 border-transparent px-4 py-2.5 text-sm data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">
Prompts
</TabsTrigger>
</TabsList>
</div>
@@ -656,10 +660,10 @@ export function GlobalSchedules() {
variant="outline"
size="sm"
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
onClick={(e) => {
e.stopPropagation()
setDeletingJob(job)
}}
onClick={(e) => {
e.stopPropagation()
openDeleteJob(job.id)
}}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
@@ -862,10 +866,10 @@ export function GlobalSchedules() {
<RunHistoryCards
runs={sortedRuns}
runsLoading={runsLoading}
onSelectRun={setSelectedRunId}
onSelectRun={selectRun}
onCancelRun={() => {
if (selectedRunId) {
const run = sortedRuns.find((r) => r.id === selectedRunId)
if (runId) {
const run = sortedRuns.find((r) => r.id === runId)
if (run) {
handleCancelRun(run.repoId, run.jobId, run.id)
}
@@ -876,30 +880,42 @@ export function GlobalSchedules() {
)}
</div>
</TabsContent>
<TabsContent value="prompts" className="mt-0 flex-1 min-h-0 flex flex-col overflow-hidden">
<div className="flex-1 min-h-0 overflow-y-auto p-4">
<PromptsTab
promptDialog={promptDialog}
templateId={templateId}
onNew={openNewTemplate}
onEdit={openEditTemplate}
onDelete={openDeleteTemplate}
onImport={openImportTemplate}
onCloseDialog={closePromptDialog}
/>
</div>
</TabsContent>
</Tabs>
<ScheduleJobDialog
open={dialogOpen}
open={dialog === 'new' || dialog === 'edit'}
onOpenChange={(open) => {
setDialogOpen(open)
if (!open) {
setEditingJob(null)
closeDialog()
setSelectedRepoId(undefined)
}
}}
job={editingJob ?? undefined}
job={dialog === 'edit' ? (editingJob ?? undefined) : undefined}
isSaving={createMutation.isPending || updateMutation.isPending}
onSubmit={editingJob ? handleUpdate : handleCreate}
onSubmit={dialog === 'edit' ? handleUpdate : handleCreate}
showRepoSelector
repoId={selectedRepoId}
onRepoChange={setSelectedRepoId}
/>
<DeleteDialog
open={deletingJob !== null}
onOpenChange={(open) => !open && setDeletingJob(null)}
open={dialog === 'delete'}
onOpenChange={(open) => !open && closeDialog()}
onConfirm={handleDelete}
onCancel={() => setDeletingJob(null)}
onCancel={closeDialog}
title="Delete Schedule"
description="This removes the job definition and all recorded run history for it."
isDeleting={deleteMutation.isPending}
+93 -66
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo } from 'react'
import { useParams } from 'react-router-dom'
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
import {
@@ -14,8 +14,8 @@ import {
} from '@/hooks/useSchedules'
import { useRepoActivity } from '@/hooks/useRepoActivity'
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
import { useScheduleUrlState } from '@/hooks/useScheduleUrlState'
import { ScheduleJobDialog, JobsTab, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
import { useScheduleTab } from '@/hooks/useMobileTabBar'
import { toUpdateScheduleRequest, getJobStatusTone } from '@/components/schedules/schedule-utils'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
@@ -28,21 +28,33 @@ import { CalendarClock, 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 { scheduleTab: activeTab, setScheduleTab: setActiveTab } = useScheduleTab()
const {
scheduleTab,
setScheduleTab,
dialog,
jobId,
runId,
openNewJob,
openEditJob,
openDeleteJob,
closeDialog,
selectRun,
selectJobAndView,
selectJobAndCloseDialog,
replaceUrlParams,
} = useScheduleUrlState()
const repoScheduleTab = scheduleTab === 'prompts' ? 'jobs' : scheduleTab
const { scheduleTarget, isLoading: scheduleTargetLoading } = useScheduleTarget(repoId)
useRepoActivity(repoId ?? 0, Boolean(scheduleTarget) && scheduleTarget?.kind === 'repo')
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 { data: selectedJob, isFetching: isJobFetching } = useRepoSchedule(repoId, jobId)
const { data: runs, isLoading: runsLoading } = useRepoScheduleRuns(repoId, jobId, 30)
const { data: selectedRunDetails, isLoading: selectedRunLoading } = useRepoScheduleRun(repoId, jobId, runId)
const createMutation = useCreateRepoSchedule()
const updateMutation = useUpdateRepoSchedule()
@@ -51,34 +63,58 @@ export function Schedules() {
const cancelRunMutation = useCancelRepoScheduleRun()
useEffect(() => {
if (!jobs?.length) {
setSelectedJobId(null)
setActiveTab('jobs')
return
if (scheduleTab === 'prompts') {
setScheduleTab('jobs')
}
}, [scheduleTab, setScheduleTab])
const stillExists = selectedJobId !== null && jobs.some((job) => job.id === selectedJobId)
if (!stillExists) {
setSelectedJobId(jobs[0]?.id ?? null)
setActiveTab('jobs')
}
}, [jobs, selectedJobId, setActiveTab])
const editingJob = useMemo<ScheduleJob | undefined>(
() => (dialog === 'edit' && jobId !== null ? jobs?.find((j) => j.id === jobId) : undefined),
[dialog, jobId, jobs],
)
useEffect(() => {
if (!runs?.length) {
setSelectedRunId(null)
if (jobs === undefined) return
if (!jobs.length) {
if (jobId !== null || scheduleTab !== 'jobs') {
replaceUrlParams((p) => {
p.delete('jobId')
p.delete('scheduleTab')
})
}
return
}
const stillExists = selectedRunId !== null && runs.some((run) => run.id === selectedRunId)
const stillExists = jobId !== null && jobs.some((job) => job.id === jobId)
if (!stillExists) {
setSelectedRunId(runs[0]?.id ?? null)
const newId = jobs[0]?.id ?? null
if (newId !== jobId || scheduleTab !== 'jobs') {
replaceUrlParams((p) => {
if (newId === null) p.delete('jobId')
else p.set('jobId', String(newId))
p.delete('scheduleTab')
})
}
}
}, [runs, selectedRunId])
}, [jobs, jobId, scheduleTab, replaceUrlParams])
useEffect(() => {
if (runs === undefined) return
if (!runs.length) {
if (runId !== null) selectRun(null)
return
}
const activeRunSummary = useMemo(() => runs?.find((run) => run.id === selectedRunId) ?? null, [runs, selectedRunId])
const stillExists = runId !== null && runs.some((run) => run.id === runId)
if (!stillExists) {
const newRunId = runs[0]?.id ?? null
if (newRunId !== runId) selectRun(newRunId)
}
}, [runs, runId, selectRun])
const activeRunSummary = useMemo(() => runs?.find((run) => run.id === runId) ?? null, [runs, runId])
const activeRun = selectedRunDetails ?? activeRunSummary
const runningRun = useMemo(() => runs?.find((run) => run.status === 'running') ?? null, [runs])
@@ -105,41 +141,36 @@ export function Schedules() {
const handleCreate = (data: CreateScheduleJobRequest) => {
createMutation.mutate({ repoId: repoId!, data }, {
onSuccess: (job) => {
setSelectedJobId(job.id)
setDialogOpen(false)
setEditingJob(undefined)
selectJobAndCloseDialog(job.id)
},
})
}
const handleUpdate = (data: CreateScheduleJobRequest) => {
if (!editingJob) {
if (dialog !== 'edit' || jobId === null) {
return
}
updateMutation.mutate({
repoId: repoId!,
jobId: editingJob.id,
jobId,
data: toUpdateScheduleRequest(data),
}, {
onSuccess: () => {
setDialogOpen(false)
setEditingJob(undefined)
closeDialog()
},
})
}
const handleDelete = () => {
if (deleteJobId === null) {
if (dialog !== 'delete' || jobId === null) {
return
}
deleteMutation.mutate({ repoId: repoId!, jobId: deleteJobId }, {
const deletedJobId = jobId
deleteMutation.mutate({ repoId: repoId!, jobId: deletedJobId }, {
onSuccess: () => {
if (selectedJobId === deleteJobId) {
setSelectedJobId(null)
}
setDeleteJobId(null)
closeDialog()
},
})
}
@@ -163,7 +194,7 @@ export function Schedules() {
runMutation.mutate({ repoId: repoId!, jobId: selectedJob.id }, {
onSuccess: (run) => {
setSelectedRunId(run.id)
selectRun(run.id)
},
})
}
@@ -179,14 +210,13 @@ export function Schedules() {
runId: activeRun.id,
}, {
onSuccess: (run) => {
setSelectedRunId(run.id)
selectRun(run.id)
},
})
}
const handleSelectJob = (jobId: number) => {
setSelectedJobId(jobId)
setActiveTab('detail')
const handleSelectJob = (id: number) => {
selectJobAndView(id)
}
return (
@@ -201,11 +231,11 @@ export function Schedules() {
<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">
<Button onClick={openNewJob} 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 h-10 w-10 p-0">
<Button onClick={openNewJob} size="sm" className="sm:hidden h-10 w-10 p-0">
<Plus className="w-5 h-5" />
</Button>
</Header.Actions>
@@ -224,7 +254,7 @@ export function Schedules() {
<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) }}>
<Button onClick={openNewJob}>
<Plus className="w-4 h-4 mr-2" />
Create First Schedule
</Button>
@@ -233,18 +263,18 @@ export function Schedules() {
</div>
) : (
<>
{activeTab === 'jobs' && (
{repoScheduleTab === 'jobs' && (
<JobsTab
jobs={jobs ?? []}
selectedJobId={selectedJobId}
selectedJobId={jobId}
onSelectJob={handleSelectJob}
/>
)}
{activeTab === 'detail' && (
{repoScheduleTab === 'detail' && (
<JobDetailTab
selectedJob={selectedJob}
onEdit={(job) => { setEditingJob(job); setDialogOpen(true) }}
onDelete={setDeleteJobId}
onEdit={(job) => openEditJob(job.id)}
onDelete={openDeleteJob}
onToggleEnabled={handleToggleEnabled}
onRunNow={handleRunNow}
updatePending={updateMutation.isPending}
@@ -253,13 +283,13 @@ export function Schedules() {
isJobFetching={isJobFetching}
/>
)}
{activeTab === 'runs' && (
{repoScheduleTab === 'runs' && (
<RunHistoryTab
repoId={repoId}
selectedJob={selectedJob}
runs={runs}
runsLoading={runsLoading}
onSelectRun={setSelectedRunId}
onSelectRun={selectRun}
activeRun={activeRun}
selectedRunLoading={selectedRunLoading}
onCancelRun={handleCancelRun}
@@ -273,30 +303,27 @@ export function Schedules() {
{hasJobs && (
<div className="sm:block hidden">
<ScheduleTabMenu
activeTab={activeTab}
onTabChange={(tab) => setActiveTab(tab)}
activeTab={repoScheduleTab as 'jobs' | 'detail' | 'runs'}
onTabChange={(tab) => setScheduleTab(tab)}
/>
</div>
)}
<ScheduleJobDialog
open={dialogOpen}
open={dialog === 'new' || dialog === 'edit'}
onOpenChange={(open) => {
setDialogOpen(open)
if (!open) {
setEditingJob(undefined)
}
if (!open) closeDialog()
}}
job={editingJob}
isSaving={createMutation.isPending || updateMutation.isPending}
onSubmit={editingJob ? handleUpdate : handleCreate}
onSubmit={dialog === 'edit' ? handleUpdate : handleCreate}
/>
<DeleteDialog
open={deleteJobId !== null}
onOpenChange={(open) => !open && setDeleteJobId(null)}
open={dialog === 'delete'}
onOpenChange={(open) => !open && closeDialog()}
onConfirm={handleDelete}
onCancel={() => setDeleteJobId(null)}
onCancel={() => closeDialog()}
title="Delete Schedule"
description="This removes the job definition and all recorded run history for it."
isDeleting={deleteMutation.isPending}
+248 -12
View File
@@ -16,7 +16,7 @@ const mocks = vi.hoisted(() => ({
useRunRepoSchedule: vi.fn(),
useCancelRepoScheduleRun: vi.fn(),
useRepoActivity: vi.fn(),
useScheduleTab: vi.fn(),
useScheduleUrlState: vi.fn(),
}))
const mockNavigate = vi.fn()
@@ -45,26 +45,59 @@ vi.mock('@/hooks/useRepoActivity', () => ({
useRepoActivity: mocks.useRepoActivity,
}))
vi.mock('@/hooks/useMobileTabBar', () => ({
useScheduleTab: mocks.useScheduleTab,
vi.mock('@/hooks/useScheduleUrlState', () => ({
useScheduleUrlState: mocks.useScheduleUrlState,
}))
vi.mock('@/components/schedules', () => ({
ScheduleJobDialog: vi.fn(() => <div>ScheduleJobDialog</div>),
ScheduleJobDialog: vi.fn(({ onOpenChange }) => (
<div>
ScheduleJobDialog
<button onClick={() => onOpenChange(false)} data-testid="close-job-dialog">Close</button>
</div>
)),
JobsTab: vi.fn(({ onSelectJob }) => (
<div>
<button onClick={() => onSelectJob(123)} data-testid="select-job">Select Job</button>
</div>
)),
JobDetailTab: vi.fn(({ onRunNow }) => (
JobDetailTab: vi.fn(({ onEdit, onDelete, onRunNow }) => (
<div>
<button onClick={onRunNow} data-testid="run-now">Run Now</button>
<button onClick={() => onEdit({ id: 123 })} data-testid="edit-job">Edit Job</button>
<button onClick={() => onDelete(123)} data-testid="delete-job">Delete Job</button>
</div>
)),
RunHistoryTab: vi.fn(() => <div>RunHistoryTab</div>),
ScheduleTabMenu: vi.fn(() => <div>ScheduleTabMenu</div>),
}))
function createMockScheduleUrlState(overrides: Record<string, unknown> = {}) {
return {
scheduleTab: 'jobs',
setScheduleTab: vi.fn(),
dialog: null,
promptDialog: null,
jobId: null,
runId: null,
templateId: null,
openNewJob: vi.fn(),
openEditJob: vi.fn(),
openDeleteJob: vi.fn(),
openNewTemplate: vi.fn(),
openEditTemplate: vi.fn(),
openDeleteTemplate: vi.fn(),
openImportTemplate: vi.fn(),
closeDialog: vi.fn(),
closePromptDialog: vi.fn(),
selectRun: vi.fn(),
selectJobAndView: vi.fn(),
selectJobAndCloseDialog: vi.fn(),
replaceUrlParams: vi.fn(),
...overrides,
}
}
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
@@ -90,10 +123,7 @@ const renderSchedules = (repoId: string) => {
describe('Schedules', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useScheduleTab.mockReturnValue({
scheduleTab: 'jobs',
setScheduleTab: vi.fn(),
})
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState())
mocks.useCreateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useUpdateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useDeleteRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
@@ -209,10 +239,9 @@ describe('Schedules', () => {
nextRunAt: null,
skillMetadata: null,
}
mocks.useScheduleTab.mockReturnValue({
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({
scheduleTab: 'detail',
setScheduleTab: vi.fn(),
})
}))
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
@@ -280,6 +309,56 @@ describe('Schedules', () => {
fireEvent.click(backButton)
expect(mockNavigate).toHaveBeenCalledWith('/repos/5')
})
it('normalizes prompts tab to jobs when jobs exist', () => {
const setScheduleTab = vi.fn()
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({
scheduleTab: 'prompts',
jobId: 123,
setScheduleTab,
}))
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
subtitle: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
backHref: '/repos/5',
},
isLoading: false,
isError: false,
})
const mockJob = {
id: 123,
name: 'Test Job',
repoId: 5,
cronExpression: null,
intervalMinutes: 30,
timezone: 'UTC',
enabled: true,
createdAt: 0,
updatedAt: 0,
scheduleMode: 'interval' as const,
agentSlug: null,
prompt: 'test',
triggerSource: 'manual' as const,
lastRunAt: null,
nextRunAt: null,
skillMetadata: null,
}
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('5')
// The normalization effect should have reset the tab to 'jobs'
expect(setScheduleTab).toHaveBeenCalledWith('jobs')
// Jobs tab content should render instead of blank
expect(screen.getByText('Select Job')).toBeInTheDocument()
})
})
describe('schedule target not found', () => {
@@ -315,4 +394,161 @@ describe('Schedules', () => {
expect(screen.getByText('Assistant not found')).toBeInTheDocument()
})
})
describe('dialog interactions', () => {
it('closing ScheduleJobDialog calls closeDialog', () => {
const closeDialog = vi.fn()
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({
dialog: 'edit',
jobId: 123,
closeDialog,
}))
const mockJob = {
id: 123,
name: 'Test Job',
repoId: 5,
cronExpression: null,
intervalMinutes: 30,
timezone: 'UTC',
enabled: true,
createdAt: 0,
updatedAt: 0,
scheduleMode: 'interval' as const,
agentSlug: null,
prompt: 'test',
triggerSource: 'manual' as const,
lastRunAt: null,
nextRunAt: null,
skillMetadata: null,
}
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
subtitle: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
backHref: '/repos/5',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('5')
const closeButton = screen.getByTestId('close-job-dialog')
fireEvent.click(closeButton)
expect(closeDialog).toHaveBeenCalled()
})
it('delete mutation success calls closeDialog', () => {
const closeDialog = vi.fn()
const deleteMutate = vi.fn((_args, { onSuccess }) => { onSuccess() })
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({
dialog: 'delete',
jobId: 123,
closeDialog,
}))
const mockJob = {
id: 123,
name: 'Test Job',
repoId: 5,
cronExpression: null,
intervalMinutes: 30,
timezone: 'UTC',
enabled: true,
createdAt: 0,
updatedAt: 0,
scheduleMode: 'interval' as const,
agentSlug: null,
prompt: 'test',
triggerSource: 'manual' as const,
lastRunAt: null,
nextRunAt: null,
skillMetadata: null,
}
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
subtitle: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
backHref: '/repos/5',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
mocks.useDeleteRepoSchedule.mockReturnValue({ mutate: deleteMutate, isPending: false })
renderSchedules('5')
// The DeleteDialog renders a Confirm button that calls onConfirm.
// Find the confirm button and click it to trigger handleDelete.
const confirmButton = screen.getByText('Delete')
fireEvent.click(confirmButton)
// The mutation runs and onSuccess calls closeDialog
expect(closeDialog).toHaveBeenCalled()
})
it('edit button on JobDetailTab calls openEditJob', () => {
const openEditJob = vi.fn()
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({
scheduleTab: 'detail',
jobId: 123,
openEditJob,
}))
const mockJob = {
id: 123,
name: 'Test Job',
repoId: 5,
cronExpression: null,
intervalMinutes: 30,
timezone: 'UTC',
enabled: true,
createdAt: 0,
updatedAt: 0,
scheduleMode: 'interval' as const,
agentSlug: null,
prompt: 'test',
triggerSource: 'manual' as const,
lastRunAt: null,
nextRunAt: null,
skillMetadata: null,
}
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
subtitle: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
backHref: '/repos/5',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('5')
const editButton = screen.getByTestId('edit-job')
fireEvent.click(editButton)
expect(openEditJob).toHaveBeenCalledWith(123)
})
})
})