From 53e3a0227ea1b5b2447125b5caf92a1387744d09 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 26 Sep 2026 00:54:54 -0400 Subject: [PATCH] fix(schedules): reject unavailable agents before creating a session --- backend/src/services/schedules.ts | 26 +++++++++++++++++++ backend/test/helpers/stub-schedule-api.ts | 5 ++++ .../services/schedules.permission.test.ts | 20 ++++++++++++++ .../ScheduleJobDialog.assistant.test.tsx | 26 ++++++++++++++++++- .../schedules/ScheduleJobDialog.tsx | 7 +++-- frontend/src/hooks/useOpenCode.ts | 3 ++- 6 files changed, 83 insertions(+), 4 deletions(-) diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 494484cb..4499a2af 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -494,6 +494,7 @@ export class ScheduleService { }) } + await this.assertAgentAvailable(runDirectory, job.agentSlug) const model = await resolveOpenCodeModel(this.openCodeClient, runDirectory, { preferredModel: job.model, }) @@ -1025,6 +1026,31 @@ export class ScheduleService { } } + /** + * OpenCode admits a prompt for a session whose agent does not exist at its location + * but never delivers it, so an unknown agent must fail the run before the session is created. + */ + private async assertAgentAvailable(directory: string, agentSlug: string | null): Promise { + if (!agentSlug) { + return + } + + let agentIds: Set + try { + const response = await this.openCodeClient.api.agent.list(openCodeLocation(directory)) + agentIds = new Set(response.data.map((agent) => agent.id)) + } catch (error) { + throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to list agents', 502) + } + + if (!agentIds.has(agentSlug)) { + throw new ScheduleServiceError( + `Agent "${agentSlug}" is not available in ${directory}. Choose an agent defined for this repo in the schedule settings, or clear the agent to use the default.`, + 400, + ) + } + } + private async resolveSkillAttachments( directory: string, skillMetadata: ScheduleJob['skillMetadata'], diff --git a/backend/test/helpers/stub-schedule-api.ts b/backend/test/helpers/stub-schedule-api.ts index d6e07c11..83688de6 100644 --- a/backend/test/helpers/stub-schedule-api.ts +++ b/backend/test/helpers/stub-schedule-api.ts @@ -11,6 +11,7 @@ export interface ScheduleApiState { messages: SessionMessageInfo[] active: Record skills: SkillInfo[] + agents: string[] createError?: Error promptError?: Error interruptError?: Error @@ -30,6 +31,7 @@ export function createStubScheduleApi(state: Partial = {}): Sc messages: [], active: {}, skills: [], + agents: ['build', 'plan'], ...state, } @@ -66,6 +68,9 @@ export function createStubScheduleApi(state: Partial = {}): Sc return { location: { directory: '' }, data: resolved.skills } }), }, + agent: { + list: vi.fn(async () => ({ location: { directory: '' }, data: resolved.agents.map((id) => ({ id, name: id })) })), + }, } return { api: api as unknown as OpenCodeApi, state: resolved } diff --git a/backend/test/services/schedules.permission.test.ts b/backend/test/services/schedules.permission.test.ts index 8e37cb92..4edee99f 100644 --- a/backend/test/services/schedules.permission.test.ts +++ b/backend/test/services/schedules.permission.test.ts @@ -222,6 +222,7 @@ describe('ScheduleService permission ruleset in session creation', () => { const stub = createStubScheduleApi({ sessionID: 'ses-perm-3', messages: [assistantMessage('', { completed: true })], + agents: ['build', 'my-agent'], }) const service = new ScheduleService( {} as never, @@ -241,4 +242,23 @@ describe('ScheduleService permission ruleset in session creation', () => { }) }) }) + + it('fails the run without creating a session when the agent is not available at the run location', async () => { + mocks.getScheduleJobById.mockReturnValue({ ...baseJob, agentSlug: 'assistant' }) + mocks.updateScheduleRun.mockReturnValue({ ...baseRun, status: 'failed' }) + + const stub = createStubScheduleApi({ agents: ['build', 'plan'] }) + const service = new ScheduleService( + {} as never, + createStubOpenCodeClient({ api: stub.api }), + mocks.stubWorktreeManager as never, + ) + + await expect(service.runJob(42, 7, 'manual')).rejects.toMatchObject({ + status: 400, + message: expect.stringContaining('Agent "assistant" is not available'), + }) + expect(stub.api.session.create).not.toHaveBeenCalled() + expect(mocks.updateScheduleRun).toHaveBeenCalledWith(expect.anything(), 42, 7, baseRun.id, expect.objectContaining({ status: 'failed' })) + }) }) diff --git a/frontend/src/components/schedules/ScheduleJobDialog.assistant.test.tsx b/frontend/src/components/schedules/ScheduleJobDialog.assistant.test.tsx index ef5aefc4..27b24a3e 100644 --- a/frontend/src/components/schedules/ScheduleJobDialog.assistant.test.tsx +++ b/frontend/src/components/schedules/ScheduleJobDialog.assistant.test.tsx @@ -10,6 +10,7 @@ Element.prototype.scrollIntoView = vi.fn() const mocks = vi.hoisted(() => ({ templates: [] as Array<{ id: number; title: string; description: string; category: string; cadenceHint: string; suggestedName: string; suggestedDescription: string; prompt: string }>, useDeletePromptTemplateMutate: vi.fn(), + useAgents: vi.fn((..._args: unknown[]) => ({ data: [] })), })) vi.mock('@/hooks/usePromptTemplates', () => ({ @@ -24,7 +25,7 @@ vi.mock('@/api/providers', () => ({ })) vi.mock('@/hooks/useOpenCode', () => ({ - useAgents: () => ({ data: [] }), + useAgents: mocks.useAgents, })) vi.mock('@/api/settings', () => ({ @@ -36,6 +37,9 @@ vi.mock('@/api/settings', () => ({ vi.mock('@/api/repos', () => ({ listRepos: () => Promise.resolve([]), listBranches: () => Promise.resolve({ branches: [], status: { ahead: 0, behind: 0 } }), + getRepo: () => Promise.reject(new Error('not used')), + getAssistantModeStatus: () => Promise.resolve({ directory: '/workspace/repos/assistant' }), + initializeAssistantMode: () => Promise.resolve(), })) function createWrapper() { @@ -143,4 +147,24 @@ describe('ScheduleJobDialog — assistant create guard', () => { expect(screen.getByRole('button', { name: /Create schedule/i })).not.toBeDisabled() }) }) + + it('lists agents from the selected repo directory instead of the default workspace', async () => { + render( + , + { wrapper: createWrapper() }, + ) + + expect(mocks.useAgents).not.toHaveBeenCalledWith(undefined, { enabled: true }) + await waitFor(() => { + expect(mocks.useAgents).toHaveBeenLastCalledWith('/workspace/repos/assistant', { enabled: true }) + }) + }) }) diff --git a/frontend/src/components/schedules/ScheduleJobDialog.tsx b/frontend/src/components/schedules/ScheduleJobDialog.tsx index c9584eb6..23d6bd6c 100644 --- a/frontend/src/components/schedules/ScheduleJobDialog.tsx +++ b/frontend/src/components/schedules/ScheduleJobDialog.tsx @@ -4,6 +4,7 @@ import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob } from '@ope import { useScheduleModels } from '@/hooks/useScheduleModels' import { resolveScheduleModel } from '@/lib/schedules/schedule-model' import { useAgents } from '@/hooks/useOpenCode' +import { useScheduleTarget } from '@/hooks/useScheduleTarget' import { settingsApi } from '@/api/settings' import { listRepos, listBranches } from '@/api/repos' import type { Repo } from '@/api/types' @@ -82,7 +83,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, [model, modelDirty, availableModelKeys, configDefaultModel], ) - const { data: agents = [] } = useAgents() + const effectiveRepoId = selectedRepoId ?? job?.repoId + const { scheduleTarget } = useScheduleTarget(open ? effectiveRepoId : undefined) + const scheduleDirectory = scheduleTarget?.fullPath + const { data: agents = [] } = useAgents(scheduleDirectory, { enabled: !!scheduleDirectory }) const { data: skills = [], isLoading: skillsLoading } = useQuery({ queryKey: ['managed-skills'], @@ -98,7 +102,6 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, staleTime: 5 * 60 * 1000, }) - const effectiveRepoId = selectedRepoId ?? job?.repoId const branchesEnabled = open && effectiveRepoId !== undefined && effectiveRepoId !== ASSISTANT_REPO_ID const { data: branchData, isLoading: branchesLoading } = useQuery({ diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index aa981a63..9bcf2a02 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -455,10 +455,11 @@ export const useSendShell = (directory?: string) => { }); }; -export const useAgents = (directory?: string) => { +export const useAgents = (directory?: string, options?: { enabled?: boolean }) => { return useQuery({ queryKey: ["opencode", "agents", directory], queryFn: () => listAgents(directory), + enabled: options?.enabled ?? true, }); };