fix(schedules): reject unavailable agents before creating a session

This commit is contained in:
Chris Scott committed 2026-09-26 00:54:54 -04:00
1 parent 5593163099
commit 53e3a0227e
6 files changed
+83 -4

No files matched your search

+26
View File
@@ -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<void> {
if (!agentSlug) {
return
}
let agentIds: Set<string>
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'],
@@ -11,6 +11,7 @@ export interface ScheduleApiState {
messages: SessionMessageInfo[]
active: Record<string, { type: 'running' }>
skills: SkillInfo[]
agents: string[]
createError?: Error
promptError?: Error
interruptError?: Error
@@ -30,6 +31,7 @@ export function createStubScheduleApi(state: Partial<ScheduleApiState> = {}): Sc
messages: [],
active: {},
skills: [],
agents: ['build', 'plan'],
...state,
}
@@ -66,6 +68,9 @@ export function createStubScheduleApi(state: Partial<ScheduleApiState> = {}): 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 }
@@ -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' }))
})
})
@@ -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(
<ScheduleJobDialog
open
onOpenChange={vi.fn()}
showRepoSelector
repoId={0}
onRepoChange={vi.fn()}
onSubmit={vi.fn()}
isSaving={false}
/>,
{ wrapper: createWrapper() },
)
expect(mocks.useAgents).not.toHaveBeenCalledWith(undefined, { enabled: true })
await waitFor(() => {
expect(mocks.useAgents).toHaveBeenLastCalledWith('/workspace/repos/assistant', { enabled: true })
})
})
})
@@ -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({
+2 -1
View File
@@ -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,
});
};