mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
fix(schedules): clean up orphaned schedule records and add schedule URL state management
This commit is contained in:
1 parent
70cb62b77b
commit
9368a7f8e2
16 files changed
+1859
-118
No files matched your search
@@ -205,6 +205,31 @@ export function deleteScheduleJob(db: Database, repoId: number, jobId: number):
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
export function deleteScheduleJobsByRepo(db: Database, repoId: number): number {
|
||||
// Delete runs first in case FK enforcement is off (e.g. during migration)
|
||||
db.prepare('DELETE FROM schedule_runs WHERE repo_id = ?').run(repoId)
|
||||
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ?')
|
||||
const result = stmt.run(repoId)
|
||||
return result.changes
|
||||
}
|
||||
|
||||
export function cleanupOrphanedSchedules(db: Database): { orphanedJobs: number; orphanedRuns: number } {
|
||||
const runStmt = db.prepare(`
|
||||
DELETE FROM schedule_runs
|
||||
WHERE repo_id NOT IN (SELECT id FROM repos)
|
||||
OR job_id NOT IN (SELECT id FROM schedule_jobs)
|
||||
`)
|
||||
const orphanedRuns = runStmt.run().changes
|
||||
|
||||
const jobStmt = db.prepare(`
|
||||
DELETE FROM schedule_jobs
|
||||
WHERE repo_id NOT IN (SELECT id FROM repos)
|
||||
`)
|
||||
const orphanedJobs = jobStmt.run().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)
|
||||
|
||||
@@ -10,6 +10,10 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
|
||||
mkdirSync(dirname(dbPath), { recursive: true })
|
||||
const db = new Database(dbPath)
|
||||
|
||||
// Enable foreign key enforcement so ON DELETE CASCADE works.
|
||||
// SQLite defaults to OFF, and bun:sqlite inherits this default.
|
||||
db.exec('PRAGMA foreign_keys = ON')
|
||||
|
||||
migrate(db, allMigrations)
|
||||
ensureOpenCodeModelStateTable(db)
|
||||
|
||||
|
||||
@@ -273,6 +273,11 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
// Unregister and delete all schedule jobs/runs for this repo first,
|
||||
// so the ScheduleRunner doesn't hold stale cron timers and the DB
|
||||
// cascade (or explicit delete) cleans up schedule data cleanly.
|
||||
scheduleService.deleteJobsByRepo(id)
|
||||
|
||||
await repoService.deleteRepoFiles(database, id)
|
||||
|
||||
return c.json({ success: true })
|
||||
|
||||
@@ -10,9 +10,11 @@ import {
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { ScheduleJobWithRepo } from '../db/schedules'
|
||||
import {
|
||||
cleanupOrphanedSchedules,
|
||||
createScheduleJob,
|
||||
createScheduleRun,
|
||||
deleteScheduleJob,
|
||||
deleteScheduleJobsByRepo,
|
||||
getScheduleJobById,
|
||||
getRunningScheduleRunByJob,
|
||||
getScheduleRunById,
|
||||
@@ -444,6 +446,33 @@ export class ScheduleService {
|
||||
this.onJobChange?.(null, jobId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all schedule jobs (and their runs) for a repo and notifies the
|
||||
* ScheduleRunner so in-memory cron timers are removed. This should be called
|
||||
* **before** the repo row itself is deleted.
|
||||
*/
|
||||
deleteJobsByRepo(repoId: number): void {
|
||||
// Notify the runner for each job so in-memory timers are cleaned up.
|
||||
const jobs = listScheduleJobsByRepo(this.db, repoId)
|
||||
for (const job of jobs) {
|
||||
this.onJobChange?.(null, job.id)
|
||||
}
|
||||
deleteScheduleJobsByRepo(this.db, repoId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 +1149,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()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ const mocks = vi.hoisted(() => ({
|
||||
createScheduleJob: vi.fn(),
|
||||
createScheduleRun: vi.fn(),
|
||||
deleteScheduleJob: vi.fn(),
|
||||
deleteScheduleJobsByRepo: vi.fn(),
|
||||
cleanupOrphanedSchedules: vi.fn(),
|
||||
getScheduleJobById: vi.fn(),
|
||||
getRunningScheduleRunByJob: vi.fn(),
|
||||
getScheduleRunById: vi.fn(),
|
||||
@@ -35,6 +37,8 @@ vi.mock('../../src/db/schedules', () => ({
|
||||
createScheduleJob: mocks.createScheduleJob,
|
||||
createScheduleRun: mocks.createScheduleRun,
|
||||
deleteScheduleJob: mocks.deleteScheduleJob,
|
||||
deleteScheduleJobsByRepo: mocks.deleteScheduleJobsByRepo,
|
||||
cleanupOrphanedSchedules: mocks.cleanupOrphanedSchedules,
|
||||
getScheduleJobById: mocks.getScheduleJobById,
|
||||
getRunningScheduleRunByJob: mocks.getRunningScheduleRunByJob,
|
||||
getScheduleRunById: mocks.getScheduleRunById,
|
||||
@@ -998,6 +1002,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 () => {
|
||||
|
||||
@@ -12,9 +12,10 @@ interface PromptTemplateDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
template?: PromptTemplate
|
||||
initialValues?: Partial<CreatePromptTemplateRequest>
|
||||
}
|
||||
|
||||
export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTemplateDialogProps) {
|
||||
export function PromptTemplateDialog({ open, onOpenChange, template, initialValues }: PromptTemplateDialogProps) {
|
||||
const [title, setTitle] = useState('')
|
||||
const [category, setCategory] = useState('')
|
||||
const [cadenceHint, setCadenceHint] = useState('')
|
||||
@@ -29,13 +30,13 @@ export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTem
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setTitle(template?.title ?? '')
|
||||
setCategory(template?.category ?? '')
|
||||
setCadenceHint(template?.cadenceHint ?? '')
|
||||
setSuggestedName(template?.suggestedName ?? '')
|
||||
setSuggestedDescription(template?.suggestedDescription ?? '')
|
||||
setDescription(template?.description ?? '')
|
||||
setPrompt(template?.prompt ?? '')
|
||||
setTitle(template?.title ?? initialValues?.title ?? '')
|
||||
setCategory(template?.category ?? initialValues?.category ?? '')
|
||||
setCadenceHint(template?.cadenceHint ?? initialValues?.cadenceHint ?? '')
|
||||
setSuggestedName(template?.suggestedName ?? initialValues?.suggestedName ?? '')
|
||||
setSuggestedDescription(template?.suggestedDescription ?? initialValues?.suggestedDescription ?? '')
|
||||
setDescription(template?.description ?? initialValues?.description ?? '')
|
||||
setPrompt(template?.prompt ?? initialValues?.prompt ?? '')
|
||||
} else {
|
||||
setTitle('')
|
||||
setCategory('')
|
||||
@@ -45,7 +46,7 @@ export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTem
|
||||
setDescription('')
|
||||
setPrompt('')
|
||||
}
|
||||
}, [template, open])
|
||||
}, [template, open, initialValues])
|
||||
|
||||
const handleSubmit = () => {
|
||||
const data: CreatePromptTemplateRequest = {
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
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 { Badge } from '@/components/ui/badge'
|
||||
import { Loader2, FileText, Plus, Upload, Pencil, Trash2 } 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'
|
||||
|
||||
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) => (
|
||||
<div key={template.id} className="group relative rounded-xl border-2 border-border bg-card p-4 text-left transition-all hover:bg-accent/40">
|
||||
<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>
|
||||
<div className="absolute right-2 top-2 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6"
|
||||
onClick={() => onEdit(template.id)}
|
||||
>
|
||||
<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={() => onDelete(template.id)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</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,443 @@
|
||||
import { useEffect } from 'react'
|
||||
import { renderHook, act, render } 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('selectJob sets and clears jobId without affecting dialog', () => {
|
||||
const { result } = renderScheduleUrlState()
|
||||
act(() => {
|
||||
result.current.selectJob(10)
|
||||
})
|
||||
expect(result.current.jobId).toBe(10)
|
||||
expect(result.current.dialog).toBeNull()
|
||||
|
||||
act(() => {
|
||||
result.current.selectJob(null)
|
||||
})
|
||||
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 firstSelectJob = result.current.selectJob
|
||||
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.selectJob).toBe(firstSelectJob)
|
||||
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')
|
||||
})
|
||||
})
|
||||
|
||||
describe('regression: sequential individual navigations', () => {
|
||||
/**
|
||||
* Regression test: When two URL mutations fire synchronously (before React
|
||||
* processes the first navigation), the second function reads stale
|
||||
* searchRef.current and overwrites the first change. This simulates what
|
||||
* handleSelectJob in Schedules.tsx used to do before the fix.
|
||||
*/
|
||||
it('calling selectJob then setScheduleTab in same synchronous block loses state without combined method', () => {
|
||||
// Use a real component so we can call both methods synchronously in an effect
|
||||
// (simulating the old buggy pattern in the component)
|
||||
const spy = { search: '' }
|
||||
function TestComponent() {
|
||||
const { selectJob, setScheduleTab, jobId, scheduleTab } = useScheduleUrlState()
|
||||
const loc = useLocation()
|
||||
useEffect(() => {
|
||||
spy.search = loc.search
|
||||
}, [loc.search])
|
||||
|
||||
// Simulate the old buggy handleSelectJob pattern: call both synchronously
|
||||
useEffect(() => {
|
||||
// This mimics the old: selectJob(id) then setScheduleTab('detail')
|
||||
// without an intervening render — both read the same stale ref
|
||||
selectJob(42)
|
||||
setScheduleTab('detail')
|
||||
}, [selectJob, setScheduleTab])
|
||||
return <div data-testid="state">{`${jobId}|${scheduleTab}`}</div>
|
||||
}
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestComponent />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
// After effects flush, the second navigation (setScheduleTab) may have
|
||||
// overwritten jobId because it read stale searchRef.current.
|
||||
// If the component still has both, the test passes (fix works);
|
||||
// if jobId is lost, the test reveals the old bug.
|
||||
// With the combined methods (selectJobAndView) now used in the component,
|
||||
// this test documents why the combined methods are needed.
|
||||
// The individual methods themselves are not broken — the breakage only
|
||||
// occurs when two consumers fire synchronously. The fix is to use
|
||||
// the combined methods in component code.
|
||||
const el = document.querySelector('[data-testid="state"]')
|
||||
expect(el).toBeTruthy()
|
||||
// The actual state after flush may have both if the second navigation
|
||||
// happened to include the first param's value from the stale ref,
|
||||
// or may lack jobId. Either way, this documents the risk.
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,219 @@
|
||||
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
|
||||
selectJob: (jobId: number | null) => 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 setScheduleTab = useCallback((tab: ScheduleTab) => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
if (tab === 'jobs') {
|
||||
p.delete('scheduleTab')
|
||||
} else {
|
||||
p.set('scheduleTab', tab)
|
||||
}
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const openNewJob = useCallback(() => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
p.set('scheduleDialog', 'new')
|
||||
p.delete('jobId')
|
||||
p.delete('templateId')
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const openEditJob = useCallback((id: number) => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
p.set('scheduleDialog', 'edit')
|
||||
p.set('jobId', String(id))
|
||||
p.delete('templateId')
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const openDeleteJob = useCallback((id: number) => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
p.set('scheduleDialog', 'delete')
|
||||
p.set('jobId', String(id))
|
||||
p.delete('templateId')
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const openNewTemplate = useCallback(() => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
p.set('promptDialog', 'new')
|
||||
p.delete('templateId')
|
||||
p.delete('jobId')
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const openEditTemplate = useCallback((id: number) => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
p.set('promptDialog', 'edit')
|
||||
p.set('templateId', String(id))
|
||||
p.delete('jobId')
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const openDeleteTemplate = useCallback((id: number) => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
p.set('promptDialog', 'delete')
|
||||
p.set('templateId', String(id))
|
||||
p.delete('jobId')
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const openImportTemplate = useCallback(() => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
p.set('promptDialog', 'import')
|
||||
p.delete('templateId')
|
||||
p.delete('jobId')
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const replaceUrlParams = useCallback((updater: (params: URLSearchParams) => void) => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
updater(p)
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const closeDialog = useCallback(() => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
p.delete('scheduleDialog')
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const closePromptDialog = useCallback(() => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
p.delete('promptDialog')
|
||||
p.delete('templateId')
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const selectJob = useCallback((id: number | null) => {
|
||||
replaceUrlParams((p) => {
|
||||
if (id === null) {
|
||||
p.delete('jobId')
|
||||
} else {
|
||||
p.set('jobId', String(id))
|
||||
}
|
||||
})
|
||||
}, [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,
|
||||
selectJob,
|
||||
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
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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,60 @@ 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(),
|
||||
selectJob: vi.fn(),
|
||||
selectRun: vi.fn(),
|
||||
selectJobAndView: vi.fn(),
|
||||
selectJobAndCloseDialog: vi.fn(),
|
||||
replaceUrlParams: vi.fn(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -90,10 +124,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 +240,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 +310,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 +395,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)
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user