diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts index 5ff232a4..f89a97a0 100644 --- a/backend/src/db/schedules.ts +++ b/backend/src/db/schedules.ts @@ -410,3 +410,77 @@ export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[ const rows = stmt.all() as ScheduleJobWithRepoRow[] return rows.map(rowToScheduleJobWithRepo) } + +export interface ScheduleRunWithContext extends ScheduleRun { + jobName: string + repoName: string + repoPath: string +} + +interface ScheduleRunWithContextRow extends ScheduleRunRow { + job_name: string + repo_path: string +} + +function rowToScheduleRunWithContext(row: ScheduleRunWithContextRow): ScheduleRunWithContext { + const run = rowToScheduleRun(row) + return { + ...run, + jobName: row.job_name, + repoName: repoNameFromPath(row.repo_path), + repoPath: row.repo_path, + } +} + +export interface ListAllRunsOptions { + limit?: number + offset?: number + status?: string + repoId?: number + jobId?: number + triggerSource?: string +} + +export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions = {}): ScheduleRunWithContext[] { + const { limit = 50, offset = 0, status, repoId, jobId, triggerSource } = options + const conditions: string[] = [] + const params: (string | number)[] = [] + + if (status) { + conditions.push('sr.status = ?') + params.push(status) + } + if (repoId !== undefined) { + conditions.push('sr.repo_id = ?') + params.push(repoId) + } + if (jobId !== undefined) { + conditions.push('sr.job_id = ?') + params.push(jobId) + } + if (triggerSource) { + conditions.push('sr.trigger_source = ?') + params.push(triggerSource) + } + + const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '' + + const stmt = db.prepare(` + SELECT + sr.id, sr.job_id, sr.repo_id, sr.trigger_source, sr.status, + sr.started_at, sr.finished_at, sr.created_at, + sr.session_id, sr.session_title, + NULL AS log_text, NULL AS response_text, sr.error_text, + sj.name AS job_name, r.local_path AS repo_path + FROM schedule_runs sr + JOIN schedule_jobs sj ON sr.job_id = sj.id + JOIN repos r ON sr.repo_id = r.id + ${whereClause} + ORDER BY sr.started_at DESC + LIMIT ? OFFSET ? + `) + + params.push(limit, offset) + const rows = stmt.all(...params) as ScheduleRunWithContextRow[] + return rows.map(rowToScheduleRunWithContext) +} diff --git a/backend/src/routes/schedules.ts b/backend/src/routes/schedules.ts index 8c968338..88737538 100644 --- a/backend/src/routes/schedules.ts +++ b/backend/src/routes/schedules.ts @@ -31,6 +31,30 @@ export function createScheduleRoutes(scheduleService: ScheduleService) { } }) + app.get('/all/runs', (c) => { + try { + const limit = parseRunListLimit(c.req.query('limit')) + const offsetStr = c.req.query('offset') + const offset = offsetStr ? Math.max(parseInt(offsetStr, 10) || 0, 0) : 0 + const status = c.req.query('status') || undefined + const repoIdStr = c.req.query('repoId') + const repoId = repoIdStr ? (() => { + const parsed = parseInt(repoIdStr, 10) + return Number.isNaN(parsed) ? undefined : parsed + })() : undefined + const jobIdStr = c.req.query('jobId') + const jobId = jobIdStr ? (() => { + const parsed = parseInt(jobIdStr, 10) + return Number.isNaN(parsed) ? undefined : parsed + })() : undefined + const triggerSource = c.req.query('triggerSource') || undefined + const runs = scheduleService.listAllRuns({ limit, offset, status, repoId, jobId, triggerSource }) + return c.json({ runs }) + } catch (error) { + return handleServiceError(c, error, 'Failed to list all schedule runs', ScheduleServiceError) + } + }) + app.get('/', (c) => { try { const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 2a4806b6..0da81157 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -17,6 +17,7 @@ import { getRunningScheduleRunByJob, getScheduleRunById, listAllScheduleJobsWithRepos, + listAllScheduleRuns, listEnabledScheduleJobs, listScheduleJobsByRepo, listRunningScheduleRuns, @@ -26,6 +27,7 @@ import { updateScheduleRun, updateScheduleRunMetadata, } from '../db/schedules' +import type { ListAllRunsOptions, ScheduleRunWithContext } from '../db/schedules' import { buildCreateSchedulePersistenceInput, buildUpdatedSchedulePersistenceInput, @@ -365,6 +367,12 @@ export class ScheduleService { return listAllScheduleJobsWithRepos(this.db) } + listAllRuns(options: ListAllRunsOptions = {}): ScheduleRunWithContext[] { + const limit = Math.min(Math.max(options.limit ?? 20, 1), 100) + const offset = Math.max(options.offset ?? 0, 0) + return listAllScheduleRuns(this.db, { ...options, limit, offset }) + } + async recoverRunningRuns(): Promise { const runningRuns = listRunningScheduleRuns(this.db) diff --git a/backend/test/db/schedules.test.ts b/backend/test/db/schedules.test.ts index 03ae96ab..db0eda22 100644 --- a/backend/test/db/schedules.test.ts +++ b/backend/test/db/schedules.test.ts @@ -440,4 +440,87 @@ describe('schedule database queries', () => { expect(run).toBeNull() }) + + it('lists all runs with context and no filters', () => { + const row = { + ...makeRunRow(), + job_name: 'Weekly summary', + repo_path: '/home/user/my-repo', + } + const stmt = { all: vi.fn().mockReturnValue([row]) } + mockDb.prepare.mockReturnValue(stmt) + + const result = schedulesDb.listAllScheduleRuns(mockDb, {}) + + expect(stmt.all).toHaveBeenCalledWith(50, 0) + expect(result).toHaveLength(1) + expect(result[0]).toMatchObject({ + id: 5, + jobName: 'Weekly summary', + repoName: 'my-repo', + repoPath: '/home/user/my-repo', + }) + }) + + it('applies status filter', () => { + const stmt = { all: vi.fn().mockReturnValue([]) } + mockDb.prepare.mockReturnValue(stmt) + + schedulesDb.listAllScheduleRuns(mockDb, { status: 'completed' }) + + expect(stmt.all).toHaveBeenCalledWith('completed', 50, 0) + expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('sr.status = ?')) + }) + + it('applies repoId filter', () => { + const stmt = { all: vi.fn().mockReturnValue([]) } + mockDb.prepare.mockReturnValue(stmt) + + schedulesDb.listAllScheduleRuns(mockDb, { repoId: 42 }) + + expect(stmt.all).toHaveBeenCalledWith(42, 50, 0) + expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('sr.repo_id = ?')) + }) + + it('applies jobId filter', () => { + const stmt = { all: vi.fn().mockReturnValue([]) } + mockDb.prepare.mockReturnValue(stmt) + + schedulesDb.listAllScheduleRuns(mockDb, { jobId: 7 }) + + expect(stmt.all).toHaveBeenCalledWith(7, 50, 0) + }) + + it('applies triggerSource filter', () => { + const stmt = { all: vi.fn().mockReturnValue([]) } + mockDb.prepare.mockReturnValue(stmt) + + schedulesDb.listAllScheduleRuns(mockDb, { triggerSource: 'manual' }) + + expect(stmt.all).toHaveBeenCalledWith('manual', 50, 0) + }) + + it('applies limit and offset', () => { + const stmt = { all: vi.fn().mockReturnValue([]) } + mockDb.prepare.mockReturnValue(stmt) + + schedulesDb.listAllScheduleRuns(mockDb, { limit: 10, offset: 20 }) + + expect(stmt.all).toHaveBeenCalledWith(10, 20) + }) + + it('returns NULL for log_text and response_text', () => { + const row = { + ...makeRunRow({ log_text: 'should be null', response_text: 'should be null' }), + job_name: 'Test job', + repo_path: '/test', + } + const stmt = { all: vi.fn().mockReturnValue([row]) } + mockDb.prepare.mockReturnValue(stmt) + + schedulesDb.listAllScheduleRuns(mockDb, {}) + + expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('NULL AS log_text')) + expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('NULL AS response_text')) + }) }) diff --git a/backend/test/routes/schedules.test.ts b/backend/test/routes/schedules.test.ts index 586afbe2..18311503 100644 --- a/backend/test/routes/schedules.test.ts +++ b/backend/test/routes/schedules.test.ts @@ -1,41 +1,32 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { Hono } from 'hono' +import { ScheduleServiceError } from '../../src/services/schedules' -const mocks = vi.hoisted(() => { - class MockScheduleServiceError extends Error { - status: number - - constructor(message: string, status: number) { - super(message) - this.status = status - } - } +const scheduleService = { + listJobs: vi.fn(), + createJob: vi.fn(), + getJob: vi.fn(), + updateJob: vi.fn(), + deleteJob: vi.fn(), + runJob: vi.fn(), + listRuns: vi.fn(), + getRun: vi.fn(), + cancelRun: vi.fn(), + listAllEnabledJobs: vi.fn(), + listAllJobsWithRepos: vi.fn(), + listAllRuns: vi.fn(), + recoverRunningRuns: vi.fn(), + setJobChangeHandler: vi.fn(), +} +vi.mock('../../src/services/schedules', async () => { + const actual = await vi.importActual('../../src/services/schedules') return { - MockScheduleServiceError, - scheduleService: { - listJobs: vi.fn(), - createJob: vi.fn(), - getJob: vi.fn(), - updateJob: vi.fn(), - deleteJob: vi.fn(), - runJob: vi.fn(), - listRuns: vi.fn(), - getRun: vi.fn(), - cancelRun: vi.fn(), - listAllEnabledJobs: vi.fn(), - listAllJobsWithRepos: vi.fn(), - recoverRunningRuns: vi.fn(), - setJobChangeHandler: vi.fn(), - }, + ...actual, + ScheduleService: vi.fn().mockImplementation(() => scheduleService), } }) -vi.mock('../../src/services/schedules', () => ({ - ScheduleService: vi.fn().mockImplementation(() => mocks.scheduleService), - ScheduleServiceError: mocks.MockScheduleServiceError, -})) - vi.mock('../../src/utils/logger', () => ({ logger: { error: vi.fn(), @@ -52,22 +43,22 @@ describe('Schedule Routes', () => { beforeEach(() => { vi.clearAllMocks() app = new Hono() - app.route('/repos/:id/schedules', createScheduleRoutes(mocks.scheduleService as unknown as import('../../src/services/schedules').ScheduleService)) + app.route('/repos/:id/schedules', createScheduleRoutes(scheduleService as unknown as import('../../src/services/schedules').ScheduleService)) }) it('lists jobs for a repo', async () => { - mocks.scheduleService.listJobs.mockReturnValue([{ id: 7, name: 'Weekly engineering summary' }]) + scheduleService.listJobs.mockReturnValue([{ id: 7, name: 'Weekly engineering summary' }]) const response = await app.request('/repos/42/schedules') const body = await response.json() as { jobs: Array<{ id: number }> } expect(response.status).toBe(200) expect(body.jobs).toHaveLength(1) - expect(mocks.scheduleService.listJobs).toHaveBeenCalledWith(42) + expect(scheduleService.listJobs).toHaveBeenCalledWith(42) }) it('creates a schedule from a valid request body', async () => { - mocks.scheduleService.createJob.mockReturnValue({ id: 7, name: 'Daily release summary' }) + scheduleService.createJob.mockReturnValue({ id: 7, name: 'Daily release summary' }) const response = await app.request('/repos/42/schedules', { method: 'POST', @@ -84,11 +75,11 @@ describe('Schedule Routes', () => { expect(response.status).toBe(201) expect(body.job.id).toBe(7) - expect(mocks.scheduleService.createJob).toHaveBeenCalledWith(42, expect.objectContaining({ name: 'Daily release summary' })) + expect(scheduleService.createJob).toHaveBeenCalledWith(42, expect.objectContaining({ name: 'Daily release summary' })) }) it('runs a schedule manually', async () => { - mocks.scheduleService.runJob.mockResolvedValue({ id: 5, status: 'running' }) + scheduleService.runJob.mockResolvedValue({ id: 5, status: 'running' }) const response = await app.request('/repos/42/schedules/7/run', { method: 'POST', @@ -97,11 +88,11 @@ describe('Schedule Routes', () => { expect(response.status).toBe(200) expect(body.run).toEqual({ id: 5, status: 'running' }) - expect(mocks.scheduleService.runJob).toHaveBeenCalledWith(42, 7, 'manual') + expect(scheduleService.runJob).toHaveBeenCalledWith(42, 7, 'manual') }) it('cancels a running schedule run', async () => { - mocks.scheduleService.cancelRun.mockResolvedValue({ id: 5, status: 'cancelled' }) + scheduleService.cancelRun.mockResolvedValue({ id: 5, status: 'cancelled' }) const response = await app.request('/repos/42/schedules/7/runs/5/cancel', { method: 'POST', @@ -110,11 +101,11 @@ describe('Schedule Routes', () => { expect(response.status).toBe(200) expect(body.run.status).toBe('cancelled') - expect(mocks.scheduleService.cancelRun).toHaveBeenCalledWith(42, 7, 5) + expect(scheduleService.cancelRun).toHaveBeenCalledWith(42, 7, 5) }) it('maps service conflicts to HTTP 409 responses', async () => { - mocks.scheduleService.runJob.mockRejectedValue(new mocks.MockScheduleServiceError('Schedule is already running', 409)) + scheduleService.runJob.mockRejectedValue(new ScheduleServiceError('Schedule is already running', 409)) const response = await app.request('/repos/42/schedules/7/run', { method: 'POST', @@ -131,12 +122,12 @@ describe('Schedule Routes', () => { expect(response.status).toBe(400) expect(body.error).toBe('Invalid repo id') - expect(mocks.scheduleService.listJobs).not.toHaveBeenCalled() + expect(scheduleService.listJobs).not.toHaveBeenCalled() }) it('loads and updates a single schedule job', async () => { - mocks.scheduleService.getJob.mockReturnValue({ id: 7, name: 'Weekly engineering summary' }) - mocks.scheduleService.updateJob.mockReturnValue({ id: 7, name: 'Updated engineering summary' }) + scheduleService.getJob.mockReturnValue({ id: 7, name: 'Weekly engineering summary' }) + scheduleService.updateJob.mockReturnValue({ id: 7, name: 'Updated engineering summary' }) const getResponse = await app.request('/repos/42/schedules/7') const getBody = await getResponse.json() as { job: { name: string } } @@ -155,9 +146,9 @@ describe('Schedule Routes', () => { }) it('lists runs, loads a single run, and deletes a schedule', async () => { - mocks.scheduleService.listRuns.mockReturnValue([{ id: 5, status: 'completed' }]) - mocks.scheduleService.getRun.mockReturnValue({ id: 5, status: 'completed' }) - mocks.scheduleService.deleteJob.mockReturnValue(undefined) + scheduleService.listRuns.mockReturnValue([{ id: 5, status: 'completed' }]) + scheduleService.getRun.mockReturnValue({ id: 5, status: 'completed' }) + scheduleService.deleteJob.mockReturnValue(undefined) const runsResponse = await app.request('/repos/42/schedules/7/runs?limit=5') const runsBody = await runsResponse.json() as { runs: Array<{ id: number }> } @@ -176,7 +167,7 @@ describe('Schedule Routes', () => { expect(runBody.run.id).toBe(5) expect(deleteResponse.status).toBe(200) expect(deleteBody.success).toBe(true) - expect(mocks.scheduleService.deleteJob).toHaveBeenCalledWith(42, 7) + expect(scheduleService.deleteJob).toHaveBeenCalledWith(42, 7) }) it('rejects non-positive run list limits', async () => { @@ -185,20 +176,20 @@ describe('Schedule Routes', () => { expect(response.status).toBe(400) expect(body.error).toBe('Limit must be greater than 0') - expect(mocks.scheduleService.listRuns).not.toHaveBeenCalled() + expect(scheduleService.listRuns).not.toHaveBeenCalled() }) it('clamps large run list limits', async () => { - mocks.scheduleService.listRuns.mockReturnValue([]) + scheduleService.listRuns.mockReturnValue([]) const response = await app.request('/repos/42/schedules/7/runs?limit=500') expect(response.status).toBe(200) - expect(mocks.scheduleService.listRuns).toHaveBeenCalledWith(42, 7, 100) + expect(scheduleService.listRuns).toHaveBeenCalledWith(42, 7, 100) }) it('returns 404 when schedule job is not found', async () => { - mocks.scheduleService.getJob.mockReturnValue(null) + scheduleService.getJob.mockReturnValue(null) const response = await app.request('/repos/42/schedules/7') const body = await response.json() as { error: string } @@ -208,7 +199,7 @@ describe('Schedule Routes', () => { }) it('creates a cron schedule from a valid request body', async () => { - mocks.scheduleService.createJob.mockReturnValue({ id: 8, name: 'Morning report' }) + scheduleService.createJob.mockReturnValue({ id: 8, name: 'Morning report' }) const response = await app.request('/repos/42/schedules', { method: 'POST', @@ -226,7 +217,7 @@ describe('Schedule Routes', () => { expect(response.status).toBe(201) expect(body.job.id).toBe(8) - expect(mocks.scheduleService.createJob).toHaveBeenCalledWith(42, expect.objectContaining({ + expect(scheduleService.createJob).toHaveBeenCalledWith(42, expect.objectContaining({ scheduleMode: 'cron', cronExpression: '0 9 * * *', timezone: 'America/New_York', @@ -234,7 +225,7 @@ describe('Schedule Routes', () => { }) it('lists all schedules across all repos', async () => { - mocks.scheduleService.listAllJobsWithRepos.mockReturnValue([ + scheduleService.listAllJobsWithRepos.mockReturnValue([ { id: 1, name: 'Job 1', repoName: 'Repo A', repoPath: '/path/a', repoUrl: 'https://repo-a' }, { id: 2, name: 'Job 2', repoName: 'Repo B', repoPath: '/path/b', repoUrl: 'https://repo-b' }, ]) @@ -249,6 +240,37 @@ describe('Schedule Routes', () => { name: 'Job 1', repoName: 'Repo A', })) - expect(mocks.scheduleService.listAllJobsWithRepos).toHaveBeenCalled() + expect(scheduleService.listAllJobsWithRepos).toHaveBeenCalled() + }) + + it('lists all runs with no filters', async () => { + scheduleService.listAllRuns.mockReturnValue([ + { id: 1, jobId: 7, repoId: 42, status: 'completed', jobName: 'Test', repoName: 'repo', repoPath: '/repo' }, + ]) + + const response = await app.request('/repos/42/schedules/all/runs') + const body = await response.json() as { runs: Array<{ id: number }> } + + expect(response.status).toBe(200) + expect(body.runs).toHaveLength(1) + expect(scheduleService.listAllRuns).toHaveBeenCalledWith(expect.objectContaining({ limit: 20, offset: 0 })) + }) + + it('passes query params to service for all runs', async () => { + scheduleService.listAllRuns.mockReturnValue([]) + + const response = await app.request('/repos/42/schedules/all/runs?limit=10&offset=5&status=failed&repoId=42&jobId=7&triggerSource=manual') + const body = await response.json() as { runs: Array } + + expect(response.status).toBe(200) + expect(body.runs).toHaveLength(0) + expect(scheduleService.listAllRuns).toHaveBeenCalledWith({ + limit: 10, + offset: 5, + status: 'failed', + repoId: 42, + jobId: 7, + triggerSource: 'manual', + }) }) })