fix(schedules): submit scheduled runs via prompt_async with SSE monitoring (#335)

* fix(schedules): submit scheduled runs via prompt_async with SSE monitoring

* fix(session): use session directory for SSE and queries when it differs from repo path
This commit is contained in:
Chris Scott authored and GitHub committed 2026-08-10 10:42:35 -04:00
1 parent 1666d0de8f
commit cfe2031c04
15 files changed
+538 -199

No files matched your search

@@ -30,6 +30,8 @@ type GeneralTabProps = {
repoOptions: ComboboxOption[]
allowExternalDirectory: boolean
onAllowExternalDirectoryChange: (value: boolean) => void
allowQuestions: boolean
onAllowQuestionsChange: (value: boolean) => void
bashDenyPatterns: string[]
onBashDenyPatternsChange: (value: string[]) => void
}
@@ -70,6 +72,8 @@ export function GeneralTab({
repoOptions,
allowExternalDirectory,
onAllowExternalDirectoryChange,
allowQuestions,
onAllowQuestionsChange,
bashDenyPatterns,
onBashDenyPatternsChange,
}: GeneralTabProps) {
@@ -178,6 +182,15 @@ export function GeneralTab({
<Switch checked={allowExternalDirectory} onCheckedChange={onAllowExternalDirectoryChange} />
</div>
</div>
<div className="rounded-lg border border-border bg-card p-4">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2">
<p className="text-sm font-medium">Allow questions</p>
<InfoHint text="Scheduled runs are unattended. When disabled, the agent's question tool is denied so a run can never stall waiting for an answer that nobody is there to give." />
</div>
<Switch checked={allowQuestions} onCheckedChange={onAllowQuestionsChange} />
</div>
</div>
<div className="rounded-lg border border-border bg-card p-4">
<div className="space-y-2">
<div className="flex items-center gap-2">
@@ -99,6 +99,11 @@ function getExternalDirSwitch() {
return screen.getAllByRole('switch')[1]
}
/** The allow-questions switch is the 3rd switch (index 2), after Enabled and external directory */
function getAllowQuestionsSwitch() {
return screen.getAllByRole('switch')[2]
}
describe('ScheduleJobDialog — permission config', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -127,6 +132,7 @@ describe('ScheduleJobDialog — permission config', () => {
const switchInput = getExternalDirSwitch()
expect(switchInput).not.toBeChecked()
expect(getAllowQuestionsSwitch()).not.toBeChecked()
})
it('initializes permission config from an existing job', async () => {
@@ -138,6 +144,7 @@ describe('ScheduleJobDialog — permission config', () => {
const job = getDefaultJob({
permissionConfig: {
allowExternalDirectory: true,
allowQuestions: true,
bashDenyPatterns: [...customPatterns],
},
})
@@ -160,6 +167,7 @@ describe('ScheduleJobDialog — permission config', () => {
const switchInput = getExternalDirSwitch()
expect(switchInput).toBeChecked()
expect(getAllowQuestionsSwitch()).toBeChecked()
})
it('submits permissionConfig in the create payload', async () => {
@@ -198,6 +206,44 @@ describe('ScheduleJobDialog — permission config', () => {
const payload = onSubmit.mock.calls[0][0]
expect(payload.permissionConfig).toEqual({
allowExternalDirectory: true,
allowQuestions: false,
bashDenyPatterns: [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS],
})
})
it('submits allowQuestions true when the questions toggle is enabled', async () => {
const onSubmit = vi.fn()
const onOpenChange = vi.fn()
const user = userEvent.setup()
render(
<ScheduleJobDialog
open
onOpenChange={onOpenChange}
onSubmit={onSubmit}
isSaving={false}
/>,
{ wrapper: createWrapper() },
)
await navigateToGeneralTab(user)
await fillRequiredFields(user)
await navigateToGeneralTab(user)
await user.click(getAllowQuestionsSwitch())
const submitButton = screen.getByRole('button', { name: /Create schedule/i })
await user.click(submitButton)
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledTimes(1)
})
const payload = onSubmit.mock.calls[0][0]
expect(payload.permissionConfig).toEqual({
allowExternalDirectory: false,
allowQuestions: true,
bashDenyPatterns: [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS],
})
})
@@ -239,6 +285,7 @@ describe('ScheduleJobDialog — permission config', () => {
const payload = onSubmit.mock.calls[0][0]
expect(payload.permissionConfig).toEqual({
allowExternalDirectory: false,
allowQuestions: false,
bashDenyPatterns: ['rm -rf *', 'sudo *'],
})
})
@@ -251,6 +298,7 @@ describe('ScheduleJobDialog — permission config', () => {
const job = getDefaultJob({
permissionConfig: {
allowExternalDirectory: false,
allowQuestions: true,
bashDenyPatterns: ['rm -rf *', 'git push --force*'],
},
})
@@ -288,6 +336,7 @@ describe('ScheduleJobDialog — permission config', () => {
const payload = onSubmit.mock.calls[0][0]
expect(payload.permissionConfig).toEqual({
allowExternalDirectory: true,
allowQuestions: true,
bashDenyPatterns: ['rm -rf *', 'git push --force*', 'sudo *'],
})
})
@@ -65,6 +65,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
const initialSkillNotesRef = useRef<string | undefined>(undefined)
const [branch, setBranch] = useState('')
const [allowExternalDirectory, setAllowExternalDirectory] = useState(false)
const [allowQuestions, setAllowQuestions] = useState(false)
const [bashDenyPatterns, setBashDenyPatterns] = useState<string[]>([...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
const [templateDialogOpen, setTemplateDialogOpen] = useState(false)
const [editingTemplate, setEditingTemplate] = useState<PromptTemplate | undefined>(undefined)
@@ -222,6 +223,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
initialSkillNotesRef.current = initialSkillNotes
setBranch(job?.branch ?? '')
setAllowExternalDirectory(job?.permissionConfig?.allowExternalDirectory ?? false)
setAllowQuestions(job?.permissionConfig?.allowQuestions ?? false)
setBashDenyPatterns(job?.permissionConfig?.bashDenyPatterns ?? [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
}, [job, open])
@@ -265,6 +267,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
branch: branch.trim() || null,
permissionConfig: {
allowExternalDirectory,
allowQuestions,
bashDenyPatterns: bashDenyPatterns.map((p) => p.trim()).filter(Boolean),
},
...(shouldIncludeSkillMetadata ? {
@@ -347,6 +350,8 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
repoOptions={repoOptions}
allowExternalDirectory={allowExternalDirectory}
onAllowExternalDirectoryChange={setAllowExternalDirectory}
allowQuestions={allowQuestions}
onAllowQuestionsChange={setAllowQuestions}
bashDenyPatterns={bashDenyPatterns}
onBashDenyPatternsChange={setBashDenyPatterns}
/>
+47 -29
View File
@@ -132,18 +132,36 @@ export function SessionDetail() {
const opcodeUrl = OPENCODE_API_ENDPOINT;
const repoDirectory = repo?.fullPath;
const sessionRouteSuffix = isAssistantSession ? '?assistant=1' : '';
const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory, sessionId);
const repoDirectory = repo?.fullPath;
const [resolvedSessionDirectory, setResolvedSessionDirectory] = useState<{ sessionId: string; directory: string } | null>(null);
const sessionDirectory = (
resolvedSessionDirectory && resolvedSessionDirectory.sessionId === sessionId
? resolvedSessionDirectory.directory
: undefined
) ?? repoDirectory;
const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, repoDirectory, { fallbackPoll: !isConnected });
const { data: session, isLoading: sessionLoading, error: sessionQueryError } = useSession(
opcodeUrl,
sessionId,
repoDirectory,
sessionDirectory,
);
useEffect(() => {
const directory = session?.directory;
if (!sessionId || !directory) return;
setResolvedSessionDirectory((current) => (
current?.sessionId === sessionId && current.directory === directory
? current
: { sessionId, directory }
));
}, [sessionId, session?.directory]);
const { isConnected, isReconnecting } = useSSE(opcodeUrl, sessionDirectory, sessionId);
const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, sessionDirectory, { fallbackPoll: !isConnected });
const messages = useMemo(() => {
if (!rawMessages) return undefined
const revertMessageID = session?.revert?.messageID
@@ -164,10 +182,10 @@ export function SessionDetail() {
contentVersion: messagesContentVersion,
onScrollStateChange: setShowScrollButton
});
const abortSession = useAbortSession(opcodeUrl, repoDirectory, sessionId);
const updateSession = useUpdateSession(opcodeUrl, repoDirectory);
const createSession = useCreateSession(opcodeUrl, repoDirectory);
const { model, modelString } = useModelSelection(opcodeUrl, repoDirectory);
const abortSession = useAbortSession(opcodeUrl, sessionDirectory, sessionId);
const updateSession = useUpdateSession(opcodeUrl, sessionDirectory);
const createSession = useCreateSession(opcodeUrl, sessionDirectory);
const { model, modelString } = useModelSelection(opcodeUrl, sessionDirectory);
const isEditingMessage = useUIState((state) => state.isEditingMessage);
const setActivePromptFileBasePath = useUIState((state) => state.setActivePromptFileBasePath);
const { isEnabled: ttsEnabled } = useTTS();
@@ -192,12 +210,12 @@ export function SessionDetail() {
const workspaceBasePath = (isAssistantSession ? assistantFileBasePath : repo?.localPath) ?? repo?.localPath;
useEffect(() => {
setActivePromptFileBasePath(repoDirectory ? workspaceBasePath ?? null : null)
setActivePromptFileBasePath(sessionDirectory ? workspaceBasePath ?? null : null)
return () => {
setActivePromptFileBasePath(null)
}
}, [repoDirectory, setActivePromptFileBasePath, workspaceBasePath])
}, [sessionDirectory, setActivePromptFileBasePath, workspaceBasePath])
useAutoPlayLastResponse({
sessionId: sessionId ?? '',
@@ -224,20 +242,20 @@ export function SessionDetail() {
}, [sessionId, minimizedQuestion])
const syncPendingActionsForSession = useCallback(async () => {
if (!repoDirectory || !sessionId) return
if (!sessionDirectory || !sessionId) return
await Promise.all([
syncPermissionsForSession(repoDirectory, sessionId),
syncQuestionsForSession(repoDirectory, sessionId),
syncPermissionsForSession(sessionDirectory, sessionId),
syncQuestionsForSession(sessionDirectory, sessionId),
])
}, [repoDirectory, sessionId, syncPermissionsForSession, syncQuestionsForSession])
}, [sessionDirectory, sessionId, syncPermissionsForSession, syncQuestionsForSession])
useQuery({
queryKey: ['opencode', 'pending-actions', opcodeUrl, sessionId, repoDirectory],
queryKey: ['opencode', 'pending-actions', opcodeUrl, sessionId, sessionDirectory],
queryFn: async () => {
await syncPendingActionsForSession()
return null
},
enabled: !!repoDirectory && !!sessionId,
enabled: !!sessionDirectory && !!sessionId,
refetchOnMount: 'always',
refetchOnReconnect: true,
refetchOnWindowFocus: true,
@@ -270,37 +288,37 @@ export function SessionDetail() {
showToast.loading('Compacting session...', { id: `compact-${sessionId}` });
try {
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
const client = createOpenCodeClient(opcodeUrl, sessionDirectory);
await client.summarizeSession(sessionId, model.providerID, model.modelID);
} catch (error) {
showToast.error(`Compact failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}, [opcodeUrl, sessionId, model, repoDirectory]);
}, [opcodeUrl, sessionId, model, sessionDirectory]);
const handleUndo = useCallback(async () => {
if (!opcodeUrl || !sessionId) return;
try {
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
const client = createOpenCodeClient(opcodeUrl, sessionDirectory);
await client.sendCommand(sessionId, { command: 'undo', arguments: '' });
} catch (error) {
showToast.error(`Undo failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}, [opcodeUrl, sessionId, repoDirectory]);
}, [opcodeUrl, sessionId, sessionDirectory]);
const handleRedo = useCallback(async () => {
if (!opcodeUrl || !sessionId) return;
try {
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
const client = createOpenCodeClient(opcodeUrl, sessionDirectory);
await client.sendCommand(sessionId, { command: 'redo', arguments: '' });
} catch (error) {
showToast.error(`Redo failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}, [opcodeUrl, sessionId, repoDirectory]);
}, [opcodeUrl, sessionId, sessionDirectory]);
const handleFork = useCallback(async () => {
if (!opcodeUrl || !sessionId) return;
try {
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
const client = createOpenCodeClient(opcodeUrl, sessionDirectory);
const forkedSession = await client.forkSession(sessionId);
if (forkedSession?.id) {
navigate(`/repos/${repoId}/sessions/${forkedSession.id}${sessionRouteSuffix}`);
@@ -309,7 +327,7 @@ export function SessionDetail() {
} catch (error) {
showToast.error(`Fork failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}, [opcodeUrl, sessionId, repoDirectory, navigate, repoId, sessionRouteSuffix]);
}, [opcodeUrl, sessionId, sessionDirectory, navigate, repoId, sessionRouteSuffix]);
const handleCloseSession = useCallback(() => {
const tab = new URLSearchParams(location.search).get('repoTab') ?? undefined;
@@ -497,7 +515,7 @@ export function SessionDetail() {
<ContextUsageIndicator
opcodeUrl={opcodeUrl}
sessionID={sessionId}
directory={repoDirectory}
directory={sessionDirectory}
isConnected={isConnected}
isReconnecting={isReconnecting}
/>
@@ -514,11 +532,11 @@ export function SessionDetail() {
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + PROMPT_OVERLAY_CLEARANCE_PX }}>
{repoLoading || sessionLoading || messagesLoading ? (
<MessageSkeleton />
) : opcodeUrl && repoDirectory ? (
) : opcodeUrl && sessionDirectory ? (
<MessageThread
opcodeUrl={opcodeUrl}
sessionID={sessionId}
directory={repoDirectory}
directory={sessionDirectory}
messages={messages}
onFileClick={handleFileClick}
onChildSessionClick={handleChildSessionClick}
@@ -527,7 +545,7 @@ export function SessionDetail() {
/>
) : null}
</div>
{opcodeUrl && repoDirectory && !isEditingMessage && (
{opcodeUrl && sessionDirectory && !isEditingMessage && (
<div
ref={promptOverlayRef}
className="absolute left-0 right-0 flex justify-center"
@@ -582,7 +600,7 @@ export function SessionDetail() {
<PromptInput
ref={promptInputRef}
opcodeUrl={opcodeUrl}
directory={repoDirectory}
directory={sessionDirectory}
sessionID={sessionId}
showScrollButton={showScrollButton && !hasPromptContent}
isSessionActive={isSessionActive}
@@ -265,6 +265,36 @@ describe('SessionDetail assistant loading at repoId=0', () => {
})
})
it('subscribes and caches using the session directory when it differs from the repo path', async () => {
mocks.useSession.mockReturnValue({
data: { id: 'sess-wt-1', directory: '/abs/worktrees/job-1-run-1', title: 'Scheduled run', time: {} },
isLoading: false,
})
renderAssistantSession('sess-wt-1')
await waitFor(() => {
expect(mocks.useSSE.mock.calls.at(-1)?.[1]).toBe('/abs/worktrees/job-1-run-1')
})
expect(mocks.useMessages.mock.calls.at(-1)?.[2]).toBe('/abs/worktrees/job-1-run-1')
})
it('keeps using the repo path when the session lives in the repo directory', async () => {
mocks.useSession.mockReturnValue({
data: { id: 'sess-asst-1', directory: '/abs/assistant', title: 'Assistant chat', time: {} },
isLoading: false,
})
renderAssistantSession('sess-asst-1')
await waitFor(() => {
expect(mocks.useSSE.mock.calls.at(-1)?.[1]).toBe('/abs/assistant')
})
expect(mocks.useMessages.mock.calls.at(-1)?.[2]).toBe('/abs/assistant')
})
it('shows the loading state for a non-assistant session whose repo has not loaded', async () => {
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })