fix(schedules): resolve older run links and index session lookups

This commit is contained in:
Chris Scott committed 2026-09-29 10:32:20 -04:00
1 parent 0e6e30890a
commit e497dbfe34
10 files changed
+470 -6

No files matched your search

@@ -0,0 +1,19 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 22,
name: 'schedule-runs-session-index',
up(db) {
db.run(`
CREATE INDEX IF NOT EXISTS idx_schedule_runs_session
ON schedule_runs(session_id, started_at DESC)
`)
},
down(db) {
db.run('DROP INDEX IF EXISTS idx_schedule_runs_session')
},
}
export default migration
+2
View File
@@ -20,6 +20,7 @@ import migration018 from './018-session-pins'
import migration019 from './019-drop-opencode-configs'
import migration020 from './020-drop-opencode-model-state'
import migration021 from './021-drop-schedule-run-workspace-id'
import migration022 from './022-schedule-runs-session-index'
export const allMigrations: Migration[] = [
migration001,
@@ -43,4 +44,5 @@ export const allMigrations: Migration[] = [
migration019,
migration020,
migration021,
migration022,
]
+6 -1
View File
@@ -598,10 +598,11 @@ export interface ListAllRunsOptions {
repoId?: number
jobId?: number
triggerSource?: string
runId?: number
}
export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions = {}): ScheduleRunWithContext[] {
const { limit = 50, offset = 0, status, repoId, jobId, triggerSource } = options
const { limit = 50, offset = 0, status, repoId, jobId, triggerSource, runId } = options
const conditions: string[] = []
const params: (string | number)[] = []
@@ -621,6 +622,10 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
conditions.push('sr.trigger_source = ?')
params.push(triggerSource)
}
if (runId !== undefined) {
conditions.push('sr.id = ?')
params.push(runId)
}
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
+19 -1
View File
@@ -19,6 +19,23 @@ function parseRunListLimit(value: string | undefined): number {
return Math.min(parsed, 100)
}
function parseRunIdFilter(value: string | undefined): number | undefined {
if (value === undefined) {
return undefined
}
if (!/^\d+$/.test(value)) {
throw new ScheduleServiceError('Invalid run id', 400)
}
const parsed = Number(value)
if (!Number.isSafeInteger(parsed) || parsed < 1) {
throw new ScheduleServiceError('Run id must be a positive integer', 400)
}
return parsed
}
export function createScheduleRoutes(scheduleService: ScheduleService) {
const app = new Hono()
@@ -48,7 +65,8 @@ export function createScheduleRoutes(scheduleService: ScheduleService) {
return Number.isNaN(parsed) ? undefined : parsed
})() : undefined
const triggerSource = c.req.query('triggerSource') || undefined
const runs = scheduleService.listAllRuns({ limit, offset, status, repoId, jobId, triggerSource })
const runId = parseRunIdFilter(c.req.query('runId'))
const runs = scheduleService.listAllRuns({ limit, offset, status, repoId, jobId, triggerSource, runId })
return c.json({ runs })
} catch (error) {
return handleServiceError(c, error, 'Failed to list all schedule runs', ScheduleServiceError)
@@ -4,6 +4,7 @@ import migration007 from '../../src/db/migrations/007-schedules'
import migration008 from '../../src/db/migrations/008-schedule-cron-support'
import migration015 from '../../src/db/migrations/015-schedule-worktree-isolation'
import migration021 from '../../src/db/migrations/021-drop-schedule-run-workspace-id'
import migration022 from '../../src/db/migrations/022-schedule-runs-session-index'
describe('schedule migrations', () => {
it('creates schedule jobs with nullable interval minutes in v7', () => {
@@ -206,3 +207,33 @@ describe('migration 021 - drop schedule run workspace id', () => {
db.close()
})
})
describe('migration 022 - schedule run session index', () => {
it('creates the composite session index on schedule_runs', () => {
const db = new Database(':memory:')
db.run('CREATE TABLE schedule_runs (id INTEGER PRIMARY KEY, session_id TEXT, started_at INTEGER NOT NULL)')
migration022.up(db)
const indexes = (db.prepare('PRAGMA index_list(schedule_runs)').all() as { name: string }[]).map((index) => index.name)
expect(indexes).toContain('idx_schedule_runs_session')
const columns = (db.prepare('PRAGMA index_info(idx_schedule_runs_session)').all() as { name: string }[]).map((column) => column.name)
expect(columns).toEqual(['session_id', 'started_at'])
db.close()
})
it('drops the index on rollback', () => {
const db = new Database(':memory:')
db.run('CREATE TABLE schedule_runs (id INTEGER PRIMARY KEY, session_id TEXT, started_at INTEGER NOT NULL)')
migration022.up(db)
migration022.down(db)
const indexes = (db.prepare('PRAGMA index_list(schedule_runs)').all() as { name: string }[]).map((index) => index.name)
expect(indexes).not.toContain('idx_schedule_runs_session')
db.close()
})
})
+19
View File
@@ -580,6 +580,25 @@ describe('schedule database queries', () => {
expect(stmt.all).toHaveBeenCalledWith('manual', 50, 0)
})
it('applies runId filter', () => {
const stmt = { all: vi.fn().mockReturnValue([]) }
mockDb.prepare.mockReturnValue(stmt)
schedulesDb.listAllScheduleRuns(mockDb, { runId: 99 })
expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('sr.id = ?'))
expect(stmt.all).toHaveBeenCalledWith(99, 50, 0)
})
it('applies runId together with other filters', () => {
const stmt = { all: vi.fn().mockReturnValue([]) }
mockDb.prepare.mockReturnValue(stmt)
schedulesDb.listAllScheduleRuns(mockDb, { runId: 99, repoId: 42, limit: 1 })
expect(stmt.all).toHaveBeenCalledWith(42, 99, 1, 0)
})
it('applies limit and offset', () => {
const stmt = { all: vi.fn().mockReturnValue([]) }
mockDb.prepare.mockReturnValue(stmt)
+29
View File
@@ -273,4 +273,33 @@ describe('Schedule Routes', () => {
triggerSource: 'manual',
})
})
it('passes a runId bound to the service for all runs', async () => {
scheduleService.listAllRuns.mockReturnValue([])
const response = await app.request('/repos/42/schedules/all/runs?runId=99')
const body = await response.json() as { runs: Array<unknown> }
expect(response.status).toBe(200)
expect(body.runs).toHaveLength(0)
expect(scheduleService.listAllRuns).toHaveBeenCalledWith(expect.objectContaining({ runId: 99 }))
})
it.each(['abc', '1abc', '1.5', '-1', ''])('rejects an invalid runId format %s for all runs', async (runId) => {
const response = await app.request(`/repos/42/schedules/all/runs?runId=${encodeURIComponent(runId)}`)
const body = await response.json() as { error: string }
expect(response.status).toBe(400)
expect(body.error).toBe('Invalid run id')
expect(scheduleService.listAllRuns).not.toHaveBeenCalled()
})
it.each(['0', '99999999999999999999'])('rejects a non-positive or unsafe runId %s for all runs', async (runId) => {
const response = await app.request(`/repos/42/schedules/all/runs?runId=${runId}`)
const body = await response.json() as { error: string }
expect(response.status).toBe(400)
expect(body.error).toBe('Run id must be a positive integer')
expect(scheduleService.listAllRuns).not.toHaveBeenCalled()
})
})
+2
View File
@@ -26,6 +26,7 @@ export interface ListAllRunsParams {
repoId?: number
jobId?: number
triggerSource?: string
runId?: number
}
export interface ScheduleCount {
@@ -45,6 +46,7 @@ export async function listAllScheduleRuns(params: ListAllRunsParams = {}): Promi
if (params.repoId !== undefined) searchParams.set('repoId', String(params.repoId))
if (params.jobId !== undefined) searchParams.set('jobId', String(params.jobId))
if (params.triggerSource) searchParams.set('triggerSource', params.triggerSource)
if (params.runId !== undefined) searchParams.set('runId', String(params.runId))
const qs = searchParams.toString()
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs${qs ? `?${qs}` : ''}`)
}
+84 -4
View File
@@ -12,7 +12,7 @@ import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
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 { CalendarClock, Loader2, Plus, ArrowLeft, Play, Pencil, Trash2, Pause, PlayCircle, Clock3, History, SlidersHorizontal, XCircle, SearchX } from 'lucide-react'
import { useScheduleUrlState } from '@/hooks/useScheduleUrlState'
import type { ScheduleTab } from '@/hooks/useScheduleUrlState'
@@ -70,6 +70,27 @@ export function GlobalSchedules() {
const { data: runsPage = [], isLoading: runsLoading } = useAllScheduleRuns(runsParams, scheduleTab === 'runs')
const selectedRunInHistory = useMemo(
() => (runId !== null ? allRuns.find((run) => run.id === runId) ?? null : null),
[allRuns, runId],
)
const selectedRunParams = useMemo(() => ({ limit: 1, runId: runId ?? undefined }), [runId])
const {
data: selectedRunPage,
isLoading: selectedRunLoading,
isError: selectedRunError,
refetch: refetchSelectedRun,
} = useAllScheduleRuns(
selectedRunParams,
scheduleTab === 'runs' && runId !== null && selectedRunInHistory === null,
)
const selectedRun = runId === null
? null
: selectedRunInHistory ?? selectedRunPage?.[0] ?? null
const createMutation = useCreateRepoSchedule()
const deleteMutation = useDeleteRepoSchedule()
const runMutation = useRunRepoSchedule()
@@ -96,8 +117,15 @@ export function GlobalSchedules() {
}
}, [runsPage])
const runsForDisplay = useMemo(() => {
if (!selectedRun || allRuns.some((run) => run.id === selectedRun.id)) {
return allRuns
}
return [...allRuns, selectedRun]
}, [allRuns, selectedRun])
const sortedRuns = useMemo(() => {
const sorted = [...allRuns]
const sorted = [...runsForDisplay]
sorted.sort((a, b) => {
switch (runSortOption) {
case 'jobName':
@@ -113,7 +141,7 @@ export function GlobalSchedules() {
}
})
return sorted
}, [allRuns, runSortOption])
}, [runsForDisplay, runSortOption])
const uniqueRepos = useMemo(() => {
const repoMap = new Map<string, { name: string; url: string }>()
@@ -312,6 +340,11 @@ export function GlobalSchedules() {
const hasJobs = jobs.length > 0
const selectedRunMissing = runId !== null && selectedRunInHistory === null
const selectedRunLookupLoading = selectedRunMissing && selectedRunLoading
const selectedRunLookupError = selectedRunMissing && selectedRunError
const selectedRunLookupNotFound = selectedRunMissing && !selectedRunLoading && !selectedRunError && selectedRun === null
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col">
<Header>
@@ -821,7 +854,54 @@ export function GlobalSchedules() {
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : allRuns.length === 0 ? (
) : selectedRunLookupLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : selectedRunLookupError ? (
<div className="flex items-center justify-center py-12">
<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">
<XCircle className="h-8 w-8 text-destructive" />
</div>
<div className="space-y-2">
<p className="text-lg font-semibold">Failed to load run</p>
<p className="text-sm text-muted-foreground">
The selected run could not be loaded.
</p>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={() => { void refetchSelectedRun() }}>
Retry
</Button>
<Button variant="outline" onClick={() => selectRun(null)}>
Back to run history
</Button>
</div>
</CardContent>
</Card>
</div>
) : selectedRunLookupNotFound ? (
<div className="flex items-center justify-center py-12">
<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">
<SearchX className="h-8 w-8 text-muted-foreground" />
</div>
<div className="space-y-2">
<p className="text-lg font-semibold">Run not found</p>
<p className="text-sm text-muted-foreground">
The requested run no longer exists.
</p>
</div>
<Button variant="outline" onClick={() => selectRun(null)}>
Back to run history
</Button>
</CardContent>
</Card>
</div>
) : sortedRuns.length === 0 ? (
<div className="flex items-center justify-center py-12">
<Card className="max-w-md border-dashed border-border/70">
<CardContent className="flex flex-col items-center gap-4 p-8 text-center">
@@ -0,0 +1,259 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { GlobalSchedules } from '../GlobalSchedules'
const mocks = vi.hoisted(() => ({
useAllSchedules: vi.fn(),
useAllScheduleRuns: vi.fn(),
useCreateRepoSchedule: vi.fn(),
useUpdateRepoSchedule: vi.fn(),
useDeleteRepoSchedule: vi.fn(),
useRunRepoSchedule: vi.fn(),
useCancelRepoScheduleRun: vi.fn(),
useScheduleUrlState: vi.fn(),
RunHistoryCards: vi.fn(() => null),
}))
vi.mock('@/hooks/useSchedules', () => ({
useAllSchedules: mocks.useAllSchedules,
useAllScheduleRuns: mocks.useAllScheduleRuns,
useCreateRepoSchedule: mocks.useCreateRepoSchedule,
useUpdateRepoSchedule: mocks.useUpdateRepoSchedule,
useDeleteRepoSchedule: mocks.useDeleteRepoSchedule,
useRunRepoSchedule: mocks.useRunRepoSchedule,
useCancelRepoScheduleRun: mocks.useCancelRepoScheduleRun,
}))
vi.mock('@/hooks/useScheduleUrlState', () => ({
useScheduleUrlState: mocks.useScheduleUrlState,
}))
vi.mock('@/components/schedules', () => ({
ScheduleJobDialog: vi.fn(() => null),
RunHistoryCards: mocks.RunHistoryCards,
PromptsTab: vi.fn(() => null),
}))
function makeRun(overrides: Record<string, unknown> = {}) {
return {
id: 1,
jobId: 7,
repoId: 42,
triggerSource: 'manual',
status: 'completed',
startedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
finishedAt: Date.UTC(2026, 2, 9, 12, 5, 0),
createdAt: Date.UTC(2026, 2, 9, 12, 0, 0),
sessionId: 'ses-1',
sessionTitle: 'Run title',
logText: null,
responseText: null,
errorText: null,
runBranch: null,
commitHash: null,
worktreePath: null,
jobName: 'Weekly summary',
repoName: 'my-repo',
repoPath: '/home/user/my-repo',
...overrides,
}
}
function createMockScheduleUrlState(overrides: Record<string, unknown> = {}) {
return {
scheduleTab: 'runs',
setScheduleTab: vi.fn(),
dialog: null,
promptDialog: null,
jobId: null,
runId: null,
templateId: null,
openNewJob: vi.fn(),
openEditJob: vi.fn(),
openDeleteJob: vi.fn(),
openNewTemplate: vi.fn(),
openEditTemplate: vi.fn(),
openDeleteTemplate: vi.fn(),
openImportTemplate: vi.fn(),
closeDialog: vi.fn(),
closePromptDialog: vi.fn(),
selectRun: vi.fn(),
selectJobAndView: vi.fn(),
selectJobAndCloseDialog: vi.fn(),
replaceUrlParams: vi.fn(),
...overrides,
}
}
let mainRunsResult: { data: unknown; isLoading: boolean; isError?: boolean }
let selectedRunResult: { data: unknown; isLoading: boolean; isError?: boolean; refetch?: () => void }
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) =>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
const renderGlobalSchedules = () => {
return render(
<MemoryRouter initialEntries={['/schedules']}>
<GlobalSchedules />
</MemoryRouter>,
{ wrapper: createWrapper() }
)
}
const runHistoryProps = () => mocks.RunHistoryCards.mock.calls.at(-1)?.[0] as {
runs: Array<{ id: number }>
selectedRunId: number | null
}
describe('GlobalSchedules run history', () => {
beforeEach(() => {
vi.clearAllMocks()
mainRunsResult = { data: [], isLoading: false }
selectedRunResult = { data: undefined, isLoading: false, isError: false }
mocks.useAllScheduleRuns.mockImplementation((params: { limit?: number }) =>
params.limit === 1 ? selectedRunResult : mainRunsResult
)
mocks.useAllSchedules.mockReturnValue({ data: [], isLoading: false, error: null })
mocks.useCreateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useUpdateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useDeleteRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useRunRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useCancelRepoScheduleRun.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState())
})
it('loads and pins a selected run outside the loaded history', () => {
const historyRuns = Array.from({ length: 50 }, (_, index) => makeRun({ id: index + 1, sessionTitle: `Run ${index + 1}` }))
mainRunsResult = { data: historyRuns, isLoading: false }
selectedRunResult = { data: [makeRun({ id: 999, sessionTitle: 'Deep linked run' })], isLoading: false, isError: false }
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999 }))
renderGlobalSchedules()
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 999 }, true)
const props = runHistoryProps()
expect(props.selectedRunId).toBe(999)
expect(props.runs.some((run) => run.id === 999)).toBe(true)
expect(screen.queryByText('No runs found')).not.toBeInTheDocument()
})
it('does not duplicate a selected run already present in history', () => {
mainRunsResult = { data: [makeRun({ id: 5 }), makeRun({ id: 6 })], isLoading: false }
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 5 }))
renderGlobalSchedules()
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 5 }, false)
const props = runHistoryProps()
expect(props.runs.filter((run) => run.id === 5)).toHaveLength(1)
})
it('shows loading instead of no runs while the selected run lookup is pending', () => {
selectedRunResult = { data: undefined, isLoading: true, isError: false }
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999 }))
const { container } = renderGlobalSchedules()
expect(screen.queryByText('No runs found')).not.toBeInTheDocument()
expect(container.querySelector('.animate-spin')).not.toBeNull()
expect(mocks.RunHistoryCards).not.toHaveBeenCalled()
})
it('shows run not found when the selected run lookup returns empty', () => {
selectedRunResult = { data: [], isLoading: false, isError: false }
const selectRun = vi.fn()
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999, selectRun }))
renderGlobalSchedules()
expect(screen.getByText('Run not found')).toBeInTheDocument()
expect(screen.queryByText('No runs found')).not.toBeInTheDocument()
expect(mocks.RunHistoryCards).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'Back to run history' }))
expect(selectRun).toHaveBeenCalledWith(null)
})
it('shows an error with retry and back actions when the selected run lookup fails', () => {
const refetch = vi.fn()
selectedRunResult = { data: undefined, isLoading: false, isError: true, refetch }
const selectRun = vi.fn()
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999, selectRun }))
renderGlobalSchedules()
expect(screen.getByText('Failed to load run')).toBeInTheDocument()
expect(screen.queryByText('No runs found')).not.toBeInTheDocument()
expect(mocks.RunHistoryCards).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
expect(refetch).toHaveBeenCalledTimes(1)
fireEvent.click(screen.getByRole('button', { name: 'Back to run history' }))
expect(selectRun).toHaveBeenCalledWith(null)
})
it('re-queries when the selected run id changes', () => {
mainRunsResult = { data: [], isLoading: false }
selectedRunResult = { data: [makeRun({ id: 999 })], isLoading: false, isError: false }
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999 }))
const { rerender } = renderGlobalSchedules()
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 999 }, true)
selectedRunResult = { data: [makeRun({ id: 1000 })], isLoading: false, isError: false }
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 1000 }))
rerender(
<MemoryRouter initialEntries={['/schedules']}>
<GlobalSchedules />
</MemoryRouter>
)
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 1000 }, true)
expect(runHistoryProps().runs.some((run) => run.id === 1000)).toBe(true)
})
it('ignores cached selected run data when the selection is cleared', () => {
mainRunsResult = { data: [], isLoading: false }
selectedRunResult = { data: [makeRun({ id: 999, sessionTitle: 'Deep linked run' })], isLoading: false, isError: false }
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999 }))
const { rerender } = renderGlobalSchedules()
expect(runHistoryProps().runs.some((run) => run.id === 999)).toBe(true)
mocks.RunHistoryCards.mockClear()
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: null }))
rerender(
<MemoryRouter initialEntries={['/schedules']}>
<GlobalSchedules />
</MemoryRouter>
)
expect(screen.getByText('No runs found')).toBeInTheDocument()
expect(mocks.RunHistoryCards).not.toHaveBeenCalled()
})
it('does not query the selected run when the runs tab is inactive', () => {
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'jobs', runId: 999 }))
renderGlobalSchedules()
expect(mocks.useAllScheduleRuns).toHaveBeenCalledWith({ limit: 1, runId: 999 }, false)
})
})