From cc89a524c4cf98030265bb51bf353b1c97ca057d Mon Sep 17 00:00:00 2001
From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
Date: Fri, 5 Jun 2026 18:07:25 -0400
Subject: [PATCH] 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
---
backend/src/db/queries.ts | 3 +-
backend/src/db/schedules.ts | 24 ++
backend/src/routes/repos.test.ts | 1 +
backend/src/routes/repos.ts | 2 +
backend/src/services/schedules.ts | 27 ++
backend/test/db/queries.test.ts | 23 +-
backend/test/db/schedules-assistant.test.ts | 11 +
backend/test/db/schedules.test.ts | 34 ++
backend/test/services/schedules.test.ts | 19 +
.../components/navigation/MobileTabBar.tsx | 7 +-
.../src/components/schedules/PromptTab.tsx | 129 +++---
.../schedules/PromptTemplateDialog.tsx | 91 +++--
.../src/components/schedules/PromptsTab.tsx | 162 ++++++++
.../schedules/__tests__/PromptsTab.test.tsx | 196 +++++++++
frontend/src/components/schedules/index.ts | 1 +
.../__tests__/useScheduleUrlState.test.tsx | 376 ++++++++++++++++++
frontend/src/hooks/useMobileTabBar.test.tsx | 80 +---
frontend/src/hooks/useMobileTabBar.ts | 38 --
frontend/src/hooks/useScheduleUrlState.ts | 207 ++++++++++
.../__tests__/markdownTemplate.test.ts | 221 ++++++++++
.../src/lib/schedules/markdownTemplate.ts | 116 ++++++
frontend/src/pages/GlobalSchedules.tsx | 78 ++--
frontend/src/pages/Schedules.tsx | 159 +++++---
.../src/pages/__tests__/Schedules.test.tsx | 260 +++++++++++-
24 files changed, 1938 insertions(+), 327 deletions(-)
create mode 100644 frontend/src/components/schedules/PromptsTab.tsx
create mode 100644 frontend/src/components/schedules/__tests__/PromptsTab.test.tsx
create mode 100644 frontend/src/hooks/__tests__/useScheduleUrlState.test.tsx
create mode 100644 frontend/src/hooks/useScheduleUrlState.ts
create mode 100644 frontend/src/lib/schedules/__tests__/markdownTemplate.test.ts
create mode 100644 frontend/src/lib/schedules/markdownTemplate.ts
diff --git a/backend/src/db/queries.ts b/backend/src/db/queries.ts
index 26a5f7e0..8bf3a0c3 100644
--- a/backend/src/db/queries.ts
+++ b/backend/src/db/queries.ts
@@ -209,7 +209,8 @@ export function updateRepoBranch(db: Database, id: number, branch: string): void
}
export function deleteRepo(db: Database, id: number): void {
+ db.prepare('DELETE FROM schedule_runs WHERE repo_id = ?').run(id)
+ db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ?').run(id)
const stmt = db.prepare('DELETE FROM repos WHERE id = ?')
stmt.run(id)
}
-
diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts
index 9480bb6d..1b08abb8 100644
--- a/backend/src/db/schedules.ts
+++ b/backend/src/db/schedules.ts
@@ -116,6 +116,12 @@ export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJo
return rows.map(rowToScheduleJob)
}
+export function listScheduleJobIdsByRepo(db: Database, repoId: number): number[] {
+ const stmt = db.prepare('SELECT id FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
+ const rows = stmt.all(repoId) as Array<{ id: number }>
+ return rows.map((row) => row.id)
+}
+
export function listEnabledScheduleJobs(db: Database): ScheduleJob[] {
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC')
const rows = stmt.all() as ScheduleJobRow[]
@@ -200,11 +206,29 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
}
export function deleteScheduleJob(db: Database, repoId: number, jobId: number): boolean {
+ db.prepare('DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ?').run(repoId, jobId)
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
const result = stmt.run(repoId, jobId)
return result.changes > 0
}
+export function cleanupOrphanedSchedules(db: Database): { orphanedJobs: number; orphanedRuns: number } {
+ const runStmt = db.prepare(`
+ DELETE FROM schedule_runs
+ WHERE (repo_id != ? AND repo_id NOT IN (SELECT id FROM repos))
+ OR job_id NOT IN (SELECT id FROM schedule_jobs)
+ `)
+ const orphanedRuns = runStmt.run(ASSISTANT_REPO_ID).changes
+
+ const jobStmt = db.prepare(`
+ DELETE FROM schedule_jobs
+ WHERE repo_id != ? AND repo_id NOT IN (SELECT id FROM repos)
+ `)
+ const orphanedJobs = jobStmt.run(ASSISTANT_REPO_ID).changes
+
+ return { orphanedJobs, orphanedRuns }
+}
+
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
diff --git a/backend/src/routes/repos.test.ts b/backend/src/routes/repos.test.ts
index 595cef83..466b3584 100644
--- a/backend/src/routes/repos.test.ts
+++ b/backend/src/routes/repos.test.ts
@@ -37,6 +37,7 @@ function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStub
listSchedules: () => [],
updateSchedule: () => {},
deleteSchedule: () => {},
+ prepareRepoDelete: () => {},
} as any
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient))
return app
diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts
index f12988c4..4771adf8 100644
--- a/backend/src/routes/repos.ts
+++ b/backend/src/routes/repos.ts
@@ -273,6 +273,8 @@ app.get('/', async (c) => {
return c.json({ error: 'Repo not found' }, 404)
}
+ scheduleService.prepareRepoDelete(id)
+
await repoService.deleteRepoFiles(database, id)
return c.json({ success: true })
diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts
index 25af1318..b2ad1d78 100644
--- a/backend/src/services/schedules.ts
+++ b/backend/src/services/schedules.ts
@@ -10,6 +10,7 @@ import {
import { getRepoById } from '../db/queries'
import type { ScheduleJobWithRepo } from '../db/schedules'
import {
+ cleanupOrphanedSchedules,
createScheduleJob,
createScheduleRun,
deleteScheduleJob,
@@ -19,6 +20,7 @@ import {
listAllScheduleJobsWithRepos,
listAllScheduleRuns,
listEnabledScheduleJobs,
+ listScheduleJobIdsByRepo,
listScheduleJobsByRepo,
listRunningScheduleRuns,
listScheduleRunsByJob,
@@ -444,6 +446,26 @@ export class ScheduleService {
this.onJobChange?.(null, jobId)
}
+ prepareRepoDelete(repoId: number): void {
+ const jobIds = listScheduleJobIdsByRepo(this.db, repoId)
+ for (const jobId of jobIds) {
+ this.onJobChange?.(null, jobId)
+ }
+ }
+
+ /**
+ * Removes any schedule_jobs and schedule_runs whose repo_id (or job_id for
+ * runs) no longer exists in the repos / schedule_jobs table. Safe to call
+ * on every startup — no-op when there are no orphans.
+ */
+ cleanupOrphanedSchedules(): { orphanedJobs: number; orphanedRuns: number } {
+ const result = cleanupOrphanedSchedules(this.db)
+ if (result.orphanedJobs > 0 || result.orphanedRuns > 0) {
+ logger.info(`Cleaned up ${result.orphanedJobs} orphaned schedule job(s) and ${result.orphanedRuns} run(s)`)
+ }
+ return result
+ }
+
listRuns(repoId: number, jobId: number, limit: number = 20): ScheduleRun[] {
this.assertJob(repoId, jobId)
return listScheduleRunsByJob(this.db, repoId, jobId, limit)
@@ -1120,6 +1142,11 @@ export class ScheduleRunner {
}
})
+ // Clean up any schedule records whose repo no longer exists. This handles
+ // leftovers from before foreign-key enforcement was enabled, and guards
+ // against edge cases where a repo row was removed outside the normal flow.
+ this.scheduleService.cleanupOrphanedSchedules()
+
await this.scheduleService.recoverRunningRuns()
this.registerAllEnabledJobs()
}
diff --git a/backend/test/db/queries.test.ts b/backend/test/db/queries.test.ts
index d909817d..62a359be 100644
--- a/backend/test/db/queries.test.ts
+++ b/backend/test/db/queries.test.ts
@@ -258,18 +258,31 @@ describe('Database Queries', () => {
})
describe('deleteRepo', () => {
- it('should delete repo by ID', () => {
- const stmt = {
+ it('should delete repo schedules before deleting repo by ID', () => {
+ const deleteRunsStmt = {
+ run: vi.fn().mockReturnValue({ changes: 2 })
+ }
+ const deleteJobsStmt = {
run: vi.fn().mockReturnValue({ changes: 1 })
}
- mockDb.prepare.mockReturnValue(stmt)
+ const deleteRepoStmt = {
+ run: vi.fn().mockReturnValue({ changes: 1 })
+ }
+ mockDb.prepare
+ .mockReturnValueOnce(deleteRunsStmt)
+ .mockReturnValueOnce(deleteJobsStmt)
+ .mockReturnValueOnce(deleteRepoStmt)
db.deleteRepo(mockDb, 1)
- expect(mockDb.prepare).toHaveBeenCalledWith(
+ expect(mockDb.prepare).toHaveBeenNthCalledWith(1, 'DELETE FROM schedule_runs WHERE repo_id = ?')
+ expect(deleteRunsStmt.run).toHaveBeenCalledWith(1)
+ expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
+ expect(deleteJobsStmt.run).toHaveBeenCalledWith(1)
+ expect(mockDb.prepare).toHaveBeenNthCalledWith(3,
'DELETE FROM repos WHERE id = ?'
)
- expect(stmt.run).toHaveBeenCalledWith(1)
+ expect(deleteRepoStmt.run).toHaveBeenCalledWith(1)
})
})
diff --git a/backend/test/db/schedules-assistant.test.ts b/backend/test/db/schedules-assistant.test.ts
index 4c271988..045fb703 100644
--- a/backend/test/db/schedules-assistant.test.ts
+++ b/backend/test/db/schedules-assistant.test.ts
@@ -3,6 +3,7 @@ import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import {
+ cleanupOrphanedSchedules,
listAllScheduleJobsWithRepos,
listAllScheduleRuns,
} from '../../src/db/schedules'
@@ -101,4 +102,14 @@ describe('assistant repo (repo_id=0) in global aggregate queries', () => {
expect(run.repoName).toBe('Assistant')
expect(run.repoPath).toBe('assistant')
})
+
+ it('cleanupOrphanedSchedules keeps assistant schedules while deleting real repo orphans', () => {
+ db.exec('DELETE FROM repos WHERE id = 1')
+
+ const result = cleanupOrphanedSchedules(db)
+
+ expect(result).toEqual({ orphanedJobs: 1, orphanedRuns: 1 })
+ expect(listAllScheduleJobsWithRepos(db).map((job) => job.repoId)).toEqual([0])
+ expect(listAllScheduleRuns(db, {}).map((run) => run.repoId)).toEqual([0])
+ })
})
diff --git a/backend/test/db/schedules.test.ts b/backend/test/db/schedules.test.ts
index 6371765b..8efab6b8 100644
--- a/backend/test/db/schedules.test.ts
+++ b/backend/test/db/schedules.test.ts
@@ -72,6 +72,19 @@ describe('schedule database queries', () => {
})
})
+ it('lists schedule job ids without loading full job rows', () => {
+ const stmt = {
+ all: vi.fn().mockReturnValue([{ id: 7 }, { id: 8 }]),
+ }
+ mockDb.prepare.mockReturnValue(stmt)
+
+ const jobIds = schedulesDb.listScheduleJobIdsByRepo(mockDb, 42)
+
+ expect(mockDb.prepare).toHaveBeenCalledWith('SELECT id FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
+ expect(stmt.all).toHaveBeenCalledWith(42)
+ expect(jobIds).toEqual([7, 8])
+ })
+
it('creates a schedule job and reloads the inserted row', () => {
const insertStmt = {
run: vi.fn().mockReturnValue({ lastInsertRowid: 7 }),
@@ -173,6 +186,27 @@ describe('schedule database queries', () => {
})
})
+ it('deletes schedule runs before deleting a schedule job', () => {
+ const deleteRunsStmt = {
+ run: vi.fn().mockReturnValue({ changes: 2 }),
+ }
+ const deleteJobStmt = {
+ run: vi.fn().mockReturnValue({ changes: 1 }),
+ }
+
+ mockDb.prepare
+ .mockReturnValueOnce(deleteRunsStmt)
+ .mockReturnValueOnce(deleteJobStmt)
+
+ const deleted = schedulesDb.deleteScheduleJob(mockDb, 42, 7)
+
+ expect(mockDb.prepare).toHaveBeenNthCalledWith(1, 'DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ?')
+ expect(deleteRunsStmt.run).toHaveBeenCalledWith(42, 7)
+ expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
+ expect(deleteJobStmt.run).toHaveBeenCalledWith(42, 7)
+ expect(deleted).toBe(true)
+ })
+
it('returns null when updating metadata for a missing run', () => {
const selectStmt = {
get: vi.fn().mockReturnValue(undefined),
diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts
index 9f51df08..b029d33e 100644
--- a/backend/test/services/schedules.test.ts
+++ b/backend/test/services/schedules.test.ts
@@ -6,11 +6,13 @@ const mocks = vi.hoisted(() => ({
createScheduleJob: vi.fn(),
createScheduleRun: vi.fn(),
deleteScheduleJob: vi.fn(),
+ cleanupOrphanedSchedules: vi.fn(),
getScheduleJobById: vi.fn(),
getRunningScheduleRunByJob: vi.fn(),
getScheduleRunById: vi.fn(),
listEnabledScheduleJobs: vi.fn(),
listRunningScheduleRuns: vi.fn(),
+ listScheduleJobIdsByRepo: vi.fn(),
listScheduleJobsByRepo: vi.fn(),
listScheduleRunsByJob: vi.fn(),
updateScheduleJob: vi.fn(),
@@ -35,11 +37,13 @@ vi.mock('../../src/db/schedules', () => ({
createScheduleJob: mocks.createScheduleJob,
createScheduleRun: mocks.createScheduleRun,
deleteScheduleJob: mocks.deleteScheduleJob,
+ cleanupOrphanedSchedules: mocks.cleanupOrphanedSchedules,
getScheduleJobById: mocks.getScheduleJobById,
getRunningScheduleRunByJob: mocks.getRunningScheduleRunByJob,
getScheduleRunById: mocks.getScheduleRunById,
listEnabledScheduleJobs: mocks.listEnabledScheduleJobs,
listRunningScheduleRuns: mocks.listRunningScheduleRuns,
+ listScheduleJobIdsByRepo: mocks.listScheduleJobIdsByRepo,
listScheduleJobsByRepo: mocks.listScheduleJobsByRepo,
listScheduleRunsByJob: mocks.listScheduleRunsByJob,
updateScheduleJob: mocks.updateScheduleJob,
@@ -724,6 +728,20 @@ describe('ScheduleService', () => {
expect(() => service.getRun(42, 7, 5)).toThrow('Run not found')
})
+ it('prepares repo deletion by unregistering repo jobs without deleting records', () => {
+ const service = new ScheduleService({} as never, createOpenCodeClientStub())
+ const onJobChange = vi.fn()
+ service.setJobChangeHandler(onJobChange)
+ mocks.listScheduleJobIdsByRepo.mockReturnValue([7, 8])
+
+ service.prepareRepoDelete(42)
+
+ expect(mocks.listScheduleJobIdsByRepo).toHaveBeenCalledWith(expect.anything(), 42)
+ expect(onJobChange).toHaveBeenCalledWith(null, 7)
+ expect(onJobChange).toHaveBeenCalledWith(null, 8)
+ expect(onJobChange).toHaveBeenCalledTimes(2)
+ })
+
it('cancels by finalizing the run when the assistant already completed', async () => {
const service = new ScheduleService({} as never, createOpenCodeClientStub())
const runningRun: ScheduleRun = {
@@ -998,6 +1016,7 @@ describe('ScheduleRunner', () => {
beforeEach(() => {
mockCronInstances.length = 0
mockCronStop.mockClear()
+ mocks.cleanupOrphanedSchedules.mockReturnValue({ orphanedJobs: 0, orphanedRuns: 0 })
})
it('recovers running runs and registers all enabled jobs on start', async () => {
diff --git a/frontend/src/components/navigation/MobileTabBar.tsx b/frontend/src/components/navigation/MobileTabBar.tsx
index 56645754..1e3b4d86 100644
--- a/frontend/src/components/navigation/MobileTabBar.tsx
+++ b/frontend/src/components/navigation/MobileTabBar.tsx
@@ -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)
diff --git a/frontend/src/components/schedules/PromptTab.tsx b/frontend/src/components/schedules/PromptTab.tsx
index 56184daa..49f7b1da 100644
--- a/frontend/src/components/schedules/PromptTab.tsx
+++ b/frontend/src/components/schedules/PromptTab.tsx
@@ -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 = (
+ <>
+
+
+ {template.category}
+
+
+ {template.cadenceHint}
+
+
+
+
{template.title}
+
{template.description}
+
+ {template.suggestedDescription}
+ {selected && (
+
+
+
+ )}
+ >
+ )
+
+ return (
+
+ {onApply ? (
+
+ ) : (
+
{content}
+ )}
+
+
+
+
+
+ )
+}
+
export function PromptTab({
prompt,
onPromptChange,
@@ -50,56 +121,14 @@ export function PromptTab({
const isSelected = selectedPromptTemplateId === template.id
return (
-
-
-
-
-
-
-
+
)
})}
diff --git a/frontend/src/components/schedules/PromptTemplateDialog.tsx b/frontend/src/components/schedules/PromptTemplateDialog.tsx
index f70dbf01..7a243f9c 100644
--- a/frontend/src/components/schedules/PromptTemplateDialog.tsx
+++ b/frontend/src/components/schedules/PromptTemplateDialog.tsx
@@ -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
+
+const INITIAL_FORM: FormData = {
+ title: '',
+ category: '',
+ cadenceHint: '',
+ suggestedName: '',
+ suggestedDescription: '',
+ description: '',
+ prompt: '',
+}
+
interface PromptTemplateDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
template?: PromptTemplate
+ initialValues?: Partial
}
-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): 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(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) => {
+ 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 (