mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
fix(schedules): clean up orphaned schedule records when repo is deleted (#255)
* fix(schedules): clean up orphaned schedule records and add schedule URL state management * refactor(schedules): consolidate schedule tab state into useScheduleUrlState * fix(schedules): cascade delete schedule runs/jobs and preserve assistant schedules in orphan cleanup * refactor(schedules): replace deleteJobsByRepo with prepareRepoDelete, add lightweight ID query, remove dead mock * refactor(schedules): consolidate PromptTemplateDialog form state into single object
This commit is contained in:
1 parent
70cb62b77b
commit
cc89a524c4
24 files changed
+1938
-327
No files matched your search
@@ -3,7 +3,8 @@ import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { FolderGit2, FolderOpen, CalendarClock, Menu, Info, History, Bot } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useMobileTabBar, useScheduleTab, type ScheduleTabKey } from '@/hooks/useMobileTabBar'
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
import { useScheduleUrlState, type ScheduleTab } from '@/hooks/useScheduleUrlState'
|
||||
import { useUIState } from '@/stores/uiStateStore'
|
||||
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
|
||||
|
||||
@@ -124,7 +125,7 @@ function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, i
|
||||
]
|
||||
}
|
||||
|
||||
function buildScheduleTabs(scheduleTab: ScheduleTabKey, setScheduleTab: (tab: ScheduleTabKey) => void): TabDef[] {
|
||||
function buildScheduleTabs(scheduleTab: ScheduleTab, setScheduleTab: (tab: ScheduleTab) => void): TabDef[] {
|
||||
return [
|
||||
{
|
||||
key: 'jobs',
|
||||
@@ -189,7 +190,7 @@ export const MobileTabBar = memo(function MobileTabBar() {
|
||||
const { pathname, search } = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const { openSheet, open, close } = useMobileTabBar()
|
||||
const { scheduleTab, setScheduleTab } = useScheduleTab()
|
||||
const { scheduleTab, setScheduleTab } = useScheduleUrlState()
|
||||
const isMobile = useMobile()
|
||||
const isMoreDrawerOpen = useUIState((state) => state.isMoreDrawerOpen)
|
||||
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
|
||||
|
||||
@@ -17,6 +17,77 @@ type PromptTabProps = {
|
||||
onNewTemplate: () => void
|
||||
}
|
||||
|
||||
type PromptTemplateCardProps = {
|
||||
template: PromptTemplate
|
||||
selected?: boolean
|
||||
onApply?: (template: PromptTemplate) => void
|
||||
onEdit: (template: PromptTemplate) => void
|
||||
onDelete: (templateId: number) => void
|
||||
}
|
||||
|
||||
export function PromptTemplateCard({ template, selected = false, onApply, onEdit, onDelete }: PromptTemplateCardProps) {
|
||||
const cardClassName = `w-full rounded-xl border-2 p-4 text-left transition-all ${
|
||||
selected
|
||||
? 'border-primary bg-primary/10 ring-2 ring-primary/30'
|
||||
: 'border-border bg-card hover:bg-accent/40'
|
||||
}`
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge className="border-transparent bg-orange-500 text-[10px] uppercase tracking-wide text-white">
|
||||
{template.category}
|
||||
</Badge>
|
||||
<Badge className="border-transparent bg-slate-600 text-[10px] uppercase tracking-wide text-white">
|
||||
{template.cadenceHint}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<p className="text-sm font-semibold">{template.title}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{template.description}</p>
|
||||
</div>
|
||||
<p className="mt-3 line-clamp-3 text-xs text-muted-foreground">{template.suggestedDescription}</p>
|
||||
{selected && (
|
||||
<div className="absolute right-2 top-2 flex h-5 w-5 items-center justify-center rounded-full bg-primary">
|
||||
<Check className="h-3 w-3 text-primary-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="group relative">
|
||||
{onApply ? (
|
||||
<button type="button" onClick={() => onApply(template)} className={cardClassName}>
|
||||
{content}
|
||||
</button>
|
||||
) : (
|
||||
<div className={cardClassName}>{content}</div>
|
||||
)}
|
||||
<div className={`absolute top-2 flex gap-1 transition-opacity ${selected || onApply ? 'right-10' : 'right-2'} ${selected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6"
|
||||
onClick={(e) => { e.stopPropagation(); onEdit(template) }}
|
||||
>
|
||||
<Pencil className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 text-destructive hover:text-destructive"
|
||||
onClick={(e) => { e.stopPropagation(); onDelete(template.id) }}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PromptTab({
|
||||
prompt,
|
||||
onPromptChange,
|
||||
@@ -50,56 +121,14 @@ export function PromptTab({
|
||||
const isSelected = selectedPromptTemplateId === template.id
|
||||
|
||||
return (
|
||||
<div key={template.id} className="relative group">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onApplyTemplate(template)}
|
||||
className={`w-full rounded-xl border-2 p-4 text-left transition-all ${
|
||||
isSelected
|
||||
? 'border-primary bg-primary/10 ring-2 ring-primary/30'
|
||||
: 'border-border bg-card hover:bg-accent/40'
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge className="text-[10px] uppercase tracking-wide border-transparent bg-orange-500 text-white">
|
||||
{template.category}
|
||||
</Badge>
|
||||
<Badge className="text-[10px] uppercase tracking-wide border-transparent bg-slate-600 text-white">
|
||||
{template.cadenceHint}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<p className="text-sm font-semibold">{template.title}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{template.description}</p>
|
||||
</div>
|
||||
<p className="mt-3 text-xs text-muted-foreground line-clamp-3">{template.suggestedDescription}</p>
|
||||
{isSelected && (
|
||||
<div className="absolute top-2 right-2 h-5 w-5 rounded-full bg-primary flex items-center justify-center">
|
||||
<Check className="h-3 w-3 text-primary-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
<div className={`absolute top-2 right-10 flex gap-1 transition-opacity ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6"
|
||||
onClick={(e) => { e.stopPropagation(); onEditTemplate(template) }}
|
||||
>
|
||||
<Pencil className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 text-destructive hover:text-destructive"
|
||||
onClick={(e) => { e.stopPropagation(); onDeleteTemplate(template.id) }}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<PromptTemplateCard
|
||||
key={template.id}
|
||||
template={template}
|
||||
selected={isSelected}
|
||||
onApply={onApplyTemplate}
|
||||
onEdit={onEditTemplate}
|
||||
onDelete={onDeleteTemplate}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import type { PromptTemplate, CreatePromptTemplateRequest } from '@opencode-manager/shared/types'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -8,54 +8,61 @@ import { Label } from '@/components/ui/label'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useCreatePromptTemplate, useUpdatePromptTemplate } from '@/hooks/usePromptTemplates'
|
||||
|
||||
type FormData = Pick<CreatePromptTemplateRequest, 'title' | 'category' | 'cadenceHint' | 'suggestedName' | 'suggestedDescription' | 'description' | 'prompt'>
|
||||
|
||||
const INITIAL_FORM: FormData = {
|
||||
title: '',
|
||||
category: '',
|
||||
cadenceHint: '',
|
||||
suggestedName: '',
|
||||
suggestedDescription: '',
|
||||
description: '',
|
||||
prompt: '',
|
||||
}
|
||||
|
||||
interface PromptTemplateDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
template?: PromptTemplate
|
||||
initialValues?: Partial<CreatePromptTemplateRequest>
|
||||
}
|
||||
|
||||
export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTemplateDialogProps) {
|
||||
const [title, setTitle] = useState('')
|
||||
const [category, setCategory] = useState('')
|
||||
const [cadenceHint, setCadenceHint] = useState('')
|
||||
const [suggestedName, setSuggestedName] = useState('')
|
||||
const [suggestedDescription, setSuggestedDescription] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [prompt, setPrompt] = useState('')
|
||||
function pickFormData(template?: PromptTemplate, initialValues?: Partial<CreatePromptTemplateRequest>): FormData {
|
||||
return {
|
||||
title: template?.title ?? initialValues?.title ?? '',
|
||||
category: template?.category ?? initialValues?.category ?? '',
|
||||
cadenceHint: template?.cadenceHint ?? initialValues?.cadenceHint ?? '',
|
||||
suggestedName: template?.suggestedName ?? initialValues?.suggestedName ?? '',
|
||||
suggestedDescription: template?.suggestedDescription ?? initialValues?.suggestedDescription ?? '',
|
||||
description: template?.description ?? initialValues?.description ?? '',
|
||||
prompt: template?.prompt ?? initialValues?.prompt ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
export function PromptTemplateDialog({ open, onOpenChange, template, initialValues }: PromptTemplateDialogProps) {
|
||||
const [form, setForm] = useState<FormData>(INITIAL_FORM)
|
||||
|
||||
const createMutation = useCreatePromptTemplate()
|
||||
const updateMutation = useUpdatePromptTemplate()
|
||||
const isSaving = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setTitle(template?.title ?? '')
|
||||
setCategory(template?.category ?? '')
|
||||
setCadenceHint(template?.cadenceHint ?? '')
|
||||
setSuggestedName(template?.suggestedName ?? '')
|
||||
setSuggestedDescription(template?.suggestedDescription ?? '')
|
||||
setDescription(template?.description ?? '')
|
||||
setPrompt(template?.prompt ?? '')
|
||||
} else {
|
||||
setTitle('')
|
||||
setCategory('')
|
||||
setCadenceHint('')
|
||||
setSuggestedName('')
|
||||
setSuggestedDescription('')
|
||||
setDescription('')
|
||||
setPrompt('')
|
||||
}
|
||||
}, [template, open])
|
||||
setForm(open ? pickFormData(template, initialValues) : INITIAL_FORM)
|
||||
}, [template, open, initialValues])
|
||||
|
||||
const handleChange = useCallback((field: keyof FormData) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
setForm((prev) => ({ ...prev, [field]: e.target.value }))
|
||||
}, [])
|
||||
|
||||
const handleSubmit = () => {
|
||||
const data: CreatePromptTemplateRequest = {
|
||||
title: title.trim(),
|
||||
category: category.trim(),
|
||||
cadenceHint: cadenceHint.trim(),
|
||||
suggestedName: suggestedName.trim(),
|
||||
suggestedDescription: suggestedDescription.trim(),
|
||||
description: description.trim(),
|
||||
prompt: prompt.trim(),
|
||||
title: form.title.trim(),
|
||||
category: form.category.trim(),
|
||||
cadenceHint: form.cadenceHint.trim(),
|
||||
suggestedName: form.suggestedName.trim(),
|
||||
suggestedDescription: form.suggestedDescription.trim(),
|
||||
description: form.description.trim(),
|
||||
prompt: form.prompt.trim(),
|
||||
}
|
||||
|
||||
if (template) {
|
||||
@@ -65,7 +72,7 @@ export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTem
|
||||
}
|
||||
}
|
||||
|
||||
const isValid = title.trim() && category.trim() && cadenceHint.trim() && suggestedName.trim() && prompt.trim()
|
||||
const isValid = form.title.trim() && form.category.trim() && form.cadenceHint.trim() && form.suggestedName.trim() && form.prompt.trim()
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -77,34 +84,34 @@ export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTem
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-title">Title</Label>
|
||||
<Input id="template-title" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Repo Health Report" />
|
||||
<Input id="template-title" value={form.title} onChange={handleChange('title')} placeholder="Repo Health Report" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-category">Category</Label>
|
||||
<Input id="template-category" value={category} onChange={(e) => setCategory(e.target.value)} placeholder="Health" />
|
||||
<Input id="template-category" value={form.category} onChange={handleChange('category')} placeholder="Health" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-cadence">Cadence hint</Label>
|
||||
<Input id="template-cadence" value={cadenceHint} onChange={(e) => setCadenceHint(e.target.value)} placeholder="Weekly" />
|
||||
<Input id="template-cadence" value={form.cadenceHint} onChange={handleChange('cadenceHint')} placeholder="Weekly" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-suggested-name">Suggested job name</Label>
|
||||
<Input id="template-suggested-name" value={suggestedName} onChange={(e) => setSuggestedName(e.target.value)} placeholder="Weekly repo health report" />
|
||||
<Input id="template-suggested-name" value={form.suggestedName} onChange={handleChange('suggestedName')} placeholder="Weekly repo health report" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-description">Description</Label>
|
||||
<Input id="template-description" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Short summary shown on the template card" />
|
||||
<Input id="template-description" value={form.description} onChange={handleChange('description')} placeholder="Short summary shown on the template card" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-suggested-description">Suggested job description</Label>
|
||||
<Input id="template-suggested-description" value={suggestedDescription} onChange={(e) => setSuggestedDescription(e.target.value)} placeholder="Pre-fills the schedule job description field" />
|
||||
<Input id="template-suggested-description" value={form.suggestedDescription} onChange={handleChange('suggestedDescription')} placeholder="Pre-fills the schedule job description field" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-prompt">Prompt</Label>
|
||||
<Textarea id="template-prompt" value={prompt} onChange={(e) => setPrompt(e.target.value)} className="min-h-[200px]" placeholder="The full prompt sent to the agent when the schedule runs." />
|
||||
<Textarea id="template-prompt" value={form.prompt} onChange={handleChange('prompt')} className="min-h-[200px]" placeholder="The full prompt sent to the agent when the schedule runs." />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-row gap-2 pt-2 border-t border-border sm:justify-end">
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import { useState, useRef } from 'react'
|
||||
import type { CreatePromptTemplateRequest } from '@opencode-manager/shared/types'
|
||||
import type { PromptDialog } from '@/hooks/useScheduleUrlState'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Loader2, FileText, Plus, Upload } from 'lucide-react'
|
||||
import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates'
|
||||
import { parseMarkdownTemplate } from '@/lib/schedules/markdownTemplate'
|
||||
import { PromptTemplateDialog } from './PromptTemplateDialog'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { PromptTemplateCard } from './PromptTab'
|
||||
|
||||
interface PromptsTabProps {
|
||||
promptDialog: PromptDialog
|
||||
templateId: number | null
|
||||
onNew: () => void
|
||||
onEdit: (id: number) => void
|
||||
onDelete: (id: number) => void
|
||||
onImport: () => void
|
||||
onCloseDialog: () => void
|
||||
}
|
||||
|
||||
export function PromptsTab({ promptDialog, templateId, onNew, onEdit, onDelete, onImport, onCloseDialog }: PromptsTabProps) {
|
||||
const [importValues, setImportValues] = useState<Partial<CreatePromptTemplateRequest> | undefined>()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const { data: templates = [], isLoading } = usePromptTemplates()
|
||||
const deleteMutation = useDeletePromptTemplate()
|
||||
|
||||
const editingTemplate = templates.find((t) => t.id === templateId)
|
||||
const dialogOpen = promptDialog === 'new' || promptDialog === 'edit' || promptDialog === 'import'
|
||||
const deleteDialogOpen = promptDialog === 'delete'
|
||||
|
||||
const handleFileImport = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (!file) return
|
||||
|
||||
const reader = new FileReader()
|
||||
reader.onload = (e) => {
|
||||
const content = e.target?.result as string
|
||||
setImportValues(parseMarkdownTemplate(content, file.name))
|
||||
onImport()
|
||||
}
|
||||
reader.readAsText(file)
|
||||
event.target.value = ''
|
||||
}
|
||||
|
||||
const handleDialogOpenChange = (open: boolean) => {
|
||||
if (!open) {
|
||||
onCloseDialog()
|
||||
setImportValues(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteConfirm = () => {
|
||||
if (templateId !== null) {
|
||||
deleteMutation.mutate(templateId, { onSuccess: onCloseDialog })
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteDialogOpenChange = (open: boolean) => {
|
||||
if (!open && !deleteMutation.isPending) {
|
||||
onCloseDialog()
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteCancel = () => {
|
||||
if (!deleteMutation.isPending) {
|
||||
onCloseDialog()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col overflow-hidden">
|
||||
<div className="flex items-center justify-between gap-2 border-b border-border px-4 py-3">
|
||||
<h2 className="text-sm font-semibold">Prompt templates</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1 text-xs"
|
||||
onClick={onNew}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
New
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1 text-xs"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="h-3 w-3" />
|
||||
Import .md
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".md,.markdown,text/markdown"
|
||||
className="hidden"
|
||||
onChange={handleFileImport}
|
||||
/>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : templates.length === 0 ? (
|
||||
<div className="flex min-h-full items-center justify-center">
|
||||
<Card className="max-w-md border-dashed border-border/70">
|
||||
<CardContent className="flex flex-col items-center gap-4 p-8 text-center">
|
||||
<div className="rounded-full border border-border bg-muted/40 p-4">
|
||||
<FileText className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-lg font-semibold">No templates yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create prompt templates to reuse across your schedules.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3 lg:grid-cols-2">
|
||||
{templates.map((template) => (
|
||||
<PromptTemplateCard
|
||||
key={template.id}
|
||||
template={template}
|
||||
onEdit={(item) => onEdit(item.id)}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<PromptTemplateDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
template={promptDialog === 'edit' ? editingTemplate : undefined}
|
||||
initialValues={promptDialog === 'import' ? importValues : undefined}
|
||||
/>
|
||||
|
||||
<DeleteDialog
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={handleDeleteDialogOpenChange}
|
||||
onConfirm={handleDeleteConfirm}
|
||||
onCancel={handleDeleteCancel}
|
||||
title="Delete template"
|
||||
description="Are you sure you want to delete this template?"
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptsTab } from '../PromptsTab'
|
||||
import type { PromptDialog } from '@/hooks/useScheduleUrlState'
|
||||
|
||||
const sampleTemplate = {
|
||||
id: 1,
|
||||
title: 'Weekly Health Report',
|
||||
category: 'Health',
|
||||
cadenceHint: 'Weekly',
|
||||
suggestedName: 'weekly-health',
|
||||
suggestedDescription: 'Runs a weekly health check',
|
||||
description: 'A weekly health report template',
|
||||
prompt: 'Run a health check on the repository',
|
||||
createdAt: 1_000_000,
|
||||
updatedAt: 1_000_000,
|
||||
}
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
deleteMutate: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/usePromptTemplates', () => ({
|
||||
usePromptTemplates: () => ({ data: [sampleTemplate], isLoading: false }),
|
||||
useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useDeletePromptTemplate: () => ({ mutate: mocks.deleteMutate, isPending: false }),
|
||||
}))
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
interface PromptsTabProps {
|
||||
promptDialog: PromptDialog
|
||||
templateId: number | null
|
||||
onNew: () => void
|
||||
onEdit: (id: number) => void
|
||||
onDelete: (id: number) => void
|
||||
onImport: () => void
|
||||
onCloseDialog: () => void
|
||||
}
|
||||
|
||||
function createProps(overrides: Partial<PromptsTabProps> = {}): PromptsTabProps {
|
||||
return {
|
||||
promptDialog: null,
|
||||
templateId: null,
|
||||
onNew: vi.fn(),
|
||||
onEdit: vi.fn(),
|
||||
onDelete: vi.fn(),
|
||||
onImport: vi.fn(),
|
||||
onCloseDialog: vi.fn(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('PromptsTab', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('renders the sample template title', () => {
|
||||
render(<PromptsTab {...createProps()} />, { wrapper: createWrapper() })
|
||||
expect(screen.getByText('Weekly Health Report')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onNew when the New button is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onNew = vi.fn()
|
||||
|
||||
render(<PromptsTab {...createProps({ onNew })} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New' }))
|
||||
expect(onNew).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('calls onDelete when the delete button on a template card is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onDelete = vi.fn()
|
||||
const { container } = render(<PromptsTab {...createProps({ onDelete })} />, {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
const deleteButton = container.querySelector('.lucide-trash2')?.closest('button')
|
||||
expect(deleteButton).toBeTruthy()
|
||||
await user.click(deleteButton!)
|
||||
expect(onDelete).toHaveBeenCalledWith(sampleTemplate.id)
|
||||
})
|
||||
|
||||
it('calls deleteMutate when confirming the delete dialog', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<PromptsTab {...createProps({ promptDialog: 'delete', templateId: sampleTemplate.id })} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Delete template')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }))
|
||||
expect(mocks.deleteMutate).toHaveBeenCalledWith(sampleTemplate.id, expect.any(Object))
|
||||
})
|
||||
|
||||
it('calls onEdit when the edit button on a template card is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onEdit = vi.fn()
|
||||
const { container } = render(<PromptsTab {...createProps({ onEdit })} />, {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
const editButton = container.querySelector('.lucide-pencil')?.closest('button')
|
||||
expect(editButton).toBeTruthy()
|
||||
await user.click(editButton!)
|
||||
expect(onEdit).toHaveBeenCalledWith(sampleTemplate.id)
|
||||
})
|
||||
|
||||
it('shows the edit dialog populated with template values', async () => {
|
||||
render(
|
||||
<PromptsTab
|
||||
{...createProps({ promptDialog: 'edit', templateId: sampleTemplate.id })}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Edit template')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const promptTextarea = screen.getByRole('textbox', { name: 'Prompt' })
|
||||
expect(promptTextarea).toHaveValue(sampleTemplate.prompt)
|
||||
})
|
||||
|
||||
it('imports a markdown file and shows parsed values in the dialog', async () => {
|
||||
const user = userEvent.setup()
|
||||
const fileContent = '---\ntitle: Imported\n---\nHello prompt'
|
||||
|
||||
const mockFileReader = {
|
||||
onload: null as ((e: { target: { result: string } }) => void) | null,
|
||||
readAsText: vi.fn(function (this: typeof mockFileReader, _file: Blob) {
|
||||
if (this.onload) {
|
||||
this.onload({ target: { result: fileContent } })
|
||||
}
|
||||
}),
|
||||
}
|
||||
vi.stubGlobal('FileReader', vi.fn(() => mockFileReader))
|
||||
|
||||
const onImport = vi.fn()
|
||||
const { container, rerender } = render(
|
||||
<PromptsTab {...createProps({ onImport })} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
const fileInput = container.querySelector('input[type="file"]')!
|
||||
const file = new File([fileContent], 'template.md', { type: 'text/markdown' })
|
||||
await user.upload(fileInput, file)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onImport).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
rerender(
|
||||
<PromptsTab
|
||||
promptDialog="import"
|
||||
templateId={null}
|
||||
onNew={vi.fn()}
|
||||
onEdit={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onImport={onImport}
|
||||
onCloseDialog={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('New template')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const promptTextarea = screen.getByRole('textbox', { name: 'Prompt' })
|
||||
expect(promptTextarea).toHaveValue('Hello prompt')
|
||||
})
|
||||
})
|
||||
@@ -6,3 +6,4 @@ export { RunDetailPanel } from './RunDetailPanel'
|
||||
export { ScheduleJobDialog } from './ScheduleJobDialog'
|
||||
export { ScheduleRunMarkdown } from './ScheduleRunMarkdown'
|
||||
export { ScheduleTabMenu } from './ScheduleTabMenu'
|
||||
export { PromptsTab } from './PromptsTab'
|
||||
Reference in new issue
Block a user