diff --git a/backend/src/db/migrations/022-schedule-runs-session-index.ts b/backend/src/db/migrations/022-schedule-runs-session-index.ts new file mode 100644 index 00000000..9e56f04b --- /dev/null +++ b/backend/src/db/migrations/022-schedule-runs-session-index.ts @@ -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 diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index c08f3e70..d3b02688 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -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, ] diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts index 97179635..57490e19 100644 --- a/backend/src/db/schedules.ts +++ b/backend/src/db/schedules.ts @@ -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 ')}` : '' diff --git a/backend/src/routes/schedules.ts b/backend/src/routes/schedules.ts index c1dad901..4c10f8f3 100644 --- a/backend/src/routes/schedules.ts +++ b/backend/src/routes/schedules.ts @@ -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) diff --git a/backend/test/db/schedule-migrations.test.ts b/backend/test/db/schedule-migrations.test.ts index fefb561b..c136df3f 100644 --- a/backend/test/db/schedule-migrations.test.ts +++ b/backend/test/db/schedule-migrations.test.ts @@ -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() + }) +}) diff --git a/backend/test/db/schedules.test.ts b/backend/test/db/schedules.test.ts index 905b43d6..1d31f8b9 100644 --- a/backend/test/db/schedules.test.ts +++ b/backend/test/db/schedules.test.ts @@ -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) diff --git a/backend/test/routes/schedules.test.ts b/backend/test/routes/schedules.test.ts index 18311503..6cfc779e 100644 --- a/backend/test/routes/schedules.test.ts +++ b/backend/test/routes/schedules.test.ts @@ -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 } + + 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() + }) }) diff --git a/frontend/src/api/schedules.ts b/frontend/src/api/schedules.ts index 24040d9d..6af986d7 100644 --- a/frontend/src/api/schedules.ts +++ b/frontend/src/api/schedules.ts @@ -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}` : ''}`) } diff --git a/frontend/src/components/schedules/RunDetailPanel.test.tsx b/frontend/src/components/schedules/RunDetailPanel.test.tsx new file mode 100644 index 00000000..aeeabd47 --- /dev/null +++ b/frontend/src/components/schedules/RunDetailPanel.test.tsx @@ -0,0 +1,130 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, waitFor, fireEvent } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { MemoryRouter } from 'react-router-dom' +import { RunDetailPanel } from './RunDetailPanel' +import type { Repo } from '@/api/types' +import type { ScheduleRun } from '@opencode-manager/shared/types' + +const mocks = vi.hoisted(() => ({ + getRepo: vi.fn(), +})) + +vi.mock('@/api/repos', () => ({ + getRepo: mocks.getRepo, +})) + +vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ + FileBrowserSheet: ({ isOpen, initialSelectedFile }: { isOpen: boolean; initialSelectedFile?: string }) => + isOpen ?
: null, +})) + +const repo: Repo = { + id: 5, + name: 'my-repo', + localPath: 'repos/my-repo', + fullPath: '/abs/repos/my-repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: 0, +} + +const run: ScheduleRun = { + id: 1, + jobId: 1, + repoId: 5, + triggerSource: 'manual', + status: 'completed', + startedAt: 0, + finishedAt: null, + createdAt: 0, + sessionId: null, + sessionTitle: null, + logText: null, + responseText: '[Report](recaps/daily.html)\n\n[Docs](https://example.com)', + errorText: null, + runBranch: null, + commitHash: null, + worktreePath: null, +} + +function renderPanel() { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + return render( + + + + + , + ) +} + +function clickLink(name: string) { + const link = screen.getByRole('link', { name }) + const event = new MouseEvent('click', { bubbles: true, cancelable: true }) + fireEvent(link, event) + return event +} + +describe('RunDetailPanel local link handling', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('prevents navigation and opens no sheet while the repo query is pending', async () => { + mocks.getRepo.mockReturnValue(new Promise(() => {})) + renderPanel() + + await screen.findByRole('status') + + const event = clickLink('Report') + + expect(event.defaultPrevented).toBe(true) + expect(screen.queryByTestId('file-browser-sheet')).not.toBeInTheDocument() + }) + + it('prevents navigation, shows a retryable error, and refetches when the repo query fails', async () => { + mocks.getRepo.mockRejectedValue(new Error('failed')) + renderPanel() + + await screen.findByRole('alert') + expect(mocks.getRepo).toHaveBeenCalledTimes(1) + + const event = clickLink('Report') + + expect(event.defaultPrevented).toBe(true) + expect(screen.queryByTestId('file-browser-sheet')).not.toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: 'Retry' })) + + await waitFor(() => expect(mocks.getRepo).toHaveBeenCalledTimes(2)) + }) + + it('opens the sheet with the resolved path once the repo is loaded and keeps external links external', async () => { + mocks.getRepo.mockResolvedValue(repo) + renderPanel() + + await waitFor(() => expect(screen.queryByRole('status')).not.toBeInTheDocument()) + + const event = clickLink('Report') + + expect(event.defaultPrevented).toBe(true) + const sheet = await screen.findByTestId('file-browser-sheet') + expect(sheet.getAttribute('data-selected-file')).toBe('repos/my-repo/recaps/daily.html') + + const docs = screen.getByRole('link', { name: 'Docs' }) + expect(docs.getAttribute('target')).toBe('_blank') + expect(docs.getAttribute('rel')).toBe('noopener noreferrer') + }) +}) diff --git a/frontend/src/components/schedules/RunDetailPanel.tsx b/frontend/src/components/schedules/RunDetailPanel.tsx index 0ad3c782..dd2ad238 100644 --- a/frontend/src/components/schedules/RunDetailPanel.tsx +++ b/frontend/src/components/schedules/RunDetailPanel.tsx @@ -23,20 +23,19 @@ interface RunDetailPanelProps { export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancelRun, cancelRunPending }: RunDetailPanelProps) { const navigate = useNavigate() const [selectedFilePath, setSelectedFilePath] = useState(null) - const { data: repo } = useQuery({ + const { data: repo, isPending: repoPending, isError: repoError, refetch: refetchRepo } = useQuery({ queryKey: ['repo', repoId], queryFn: () => getRepo(repoId), }) - const handleOpenLocalPath = repo - ? (linkPath: string) => { - setSelectedFilePath(getWorkspaceFilePath(linkPath, { - directory: activeRun?.worktreePath ?? repo.fullPath, - repoFullPath: repo.fullPath, - repoLocalPath: repo.localPath, - })) - } - : undefined + const handleOpenLocalPath = (linkPath: string) => { + if (!repo) return + setSelectedFilePath(getWorkspaceFilePath(linkPath, { + directory: activeRun?.worktreePath ?? repo.fullPath, + repoFullPath: repo.fullPath, + repoLocalPath: repo.localPath, + })) + } if (selectedRunLoading && !activeRun) { return ( @@ -62,7 +61,7 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel {activeRun.status === 'cancelled' ? 'Details' : 'Error'}
- {(activeRun.status === 'running' || activeRun.sessionId || activeRun.responseText) && ( + {(activeRun.status === 'running' || activeRun.sessionId) && (
{sessionId && ( @@ -71,13 +70,15 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel )}
- + {activeRun.status === 'running' && ( + + )}
)} - + {selectedRunLoading && !activeRun ? (
) : ( @@ -88,14 +89,25 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel {selectedRunLoading && !activeRun ? (
) : activeRun.responseText ? ( -
- -
+ <> + {repoPending && ( +
Loading repository details for local links.
+ )} + {repoError && ( +
+ Could not load repository details for local links. + +
+ )} +
+ +
+ ) : (
No assistant output captured.
)}
- + {selectedRunLoading && !activeRun ? (
) : ( diff --git a/frontend/src/components/schedules/RunHistoryCards.tsx b/frontend/src/components/schedules/RunHistoryCards.tsx index 1b44a314..21cb9351 100644 --- a/frontend/src/components/schedules/RunHistoryCards.tsx +++ b/frontend/src/components/schedules/RunHistoryCards.tsx @@ -78,20 +78,17 @@ export function RunHistoryCards({ } return ( -
-
- {runs.map((run, index) => { - const isExpanded = expandedRunId === run.id - const displayRun = isExpanded && runDetail ? runDetail : run +
+ {runs.map((run) => { + const isExpanded = expandedRunId === run.id + const displayRun = isExpanded && runDetail ? runDetail : run - return ( -
-
+ return ( +
+
)} -
- {isExpanded && ( -
-
- -
-
- )}
- ) - })} -
+ {isExpanded && ( +
+ +
+ )} +
+ ) + })}
) } diff --git a/frontend/src/components/schedules/RunHistoryTab.tsx b/frontend/src/components/schedules/RunHistoryTab.tsx index 066b9864..dc32b3b9 100644 --- a/frontend/src/components/schedules/RunHistoryTab.tsx +++ b/frontend/src/components/schedules/RunHistoryTab.tsx @@ -71,17 +71,19 @@ export function RunHistoryTab({
- +
+ +
-
+
(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() @@ -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 && selectedRun === null + const selectedRunLookupNotFound = selectedRunMissing && !selectedRunLoading && !selectedRunError && selectedRun === null + return (
@@ -355,7 +388,7 @@ export function GlobalSchedules() {
-
+
Filter by repo:
-
+
{!hasJobs ? (
@@ -667,7 +700,7 @@ export function GlobalSchedules() { -
+
Filter by repo:
-
+
{runsLoading && allRuns.length === 0 ? (
- ) : allRuns.length === 0 ? ( -
+ ) : selectedRunLookupLoading ? ( +
+ +
+ ) : selectedRunLookupError ? ( +
+ + +
+ +
+
+

Failed to load run

+

+ The selected run could not be loaded. +

+
+
+ + +
+
+
+
+ ) : selectedRunLookupNotFound ? ( +
+ + +
+ +
+
+

Run not found

+

+ The requested run no longer exists. +

+
+ +
+
+
+ ) : sortedRuns.length === 0 ? ( +
diff --git a/frontend/src/pages/__tests__/GlobalSchedules.test.tsx b/frontend/src/pages/__tests__/GlobalSchedules.test.tsx new file mode 100644 index 00000000..6287ddb5 --- /dev/null +++ b/frontend/src/pages/__tests__/GlobalSchedules.test.tsx @@ -0,0 +1,273 @@ +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 = {}) { + 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 = {}) { + 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 }) => + {children} +} + +const renderGlobalSchedules = () => { + return render( + + + , + { 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('renders the cached selected run when a background refetch fails', () => { + selectedRunResult = { data: [makeRun({ id: 999, sessionTitle: 'Deep linked run' })], isLoading: false, isError: true } + mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'runs', runId: 999 })) + + renderGlobalSchedules() + + expect(screen.queryByText('Failed to load run')).not.toBeInTheDocument() + expect(screen.queryByText('Run not found')).not.toBeInTheDocument() + expect(mocks.RunHistoryCards).toHaveBeenCalled() + const props = runHistoryProps() + expect(props.selectedRunId).toBe(999) + expect(props.runs.filter((run) => run.id === 999)).toHaveLength(1) + }) + + 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( + + + + ) + + 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( + + + + ) + + 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) + }) +})