Skip to content

The agent that grows with you

fix(desktop): cron Pause, Stop polling and connection switches behave

Tekniume3353d52b8d4
diff --git a/apps/desktop/src/app/cron/cron-actions.ts b/apps/desktop/src/app/cron/cron-actions.ts
index e49c541f649..7d9895a8388 100644
--- a/apps/desktop/src/app/cron/cron-actions.ts
+++ b/apps/desktop/src/app/cron/cron-actions.ts
@@ -18,7 +18,7 @@ export interface CronMutationRefreshResult<T> extends CronTriggerRefreshResult {
value: T | null
}
-function cronRequestScope(profile: string): string {
+export function cronRequestScope(profile: string): string {
return `${getApiRequestConnection() ?? ''}\u0000${profile}`
}
diff --git a/apps/desktop/src/app/cron/index.tsx b/apps/desktop/src/app/cron/index.tsx
index 5f54952ee27..25a5ad867c8 100644
--- a/apps/desktop/src/app/cron/index.tsx
+++ b/apps/desktop/src/app/cron/index.tsx
@@ -906,7 +906,9 @@ function CronJobDetail({
stopping
}: CronJobDetailProps) {
const state = runLive ? 'running' : jobState(job)
- const isPaused = state === 'paused'
+ // The pill shows the live run; Pause/Resume acts on the saved schedule state, which a running
+ // paused job still has (handlePauseResume reads jobState too).
+ const isPaused = jobState(job) === 'paused'
const deliver = jobDeliver(job)
const prompt = jobPrompt(job)
const scriptOnly = jobIsScriptOnly(job)
diff --git a/apps/desktop/src/app/cron/run-stop.test.tsx b/apps/desktop/src/app/cron/run-stop.test.tsx
new file mode 100644
index 00000000000..fa55934848d
--- /dev/null
+++ b/apps/desktop/src/app/cron/run-stop.test.tsx
@@ -0,0 +1,135 @@
+// @vitest-environment jsdom
+import { QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, render, renderHook, screen } from '@testing-library/react'
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type * as HermesApi from '@/hermes'
+import type { CronJob } from '@/hermes'
+import type { Translations } from '@/i18n'
+import { queryClient } from '@/lib/query-client'
+import { $cronJobs, invalidateCronJobsRequests, setCronFocusJobId, setCronJobs } from '@/store/cron'
+import { setChangeEventsAvailable } from '@/store/live-sync'
+import { notify } from '@/store/notifications'
+import type { CronCancelResult } from '@/types/hermes'
+
+import { useCronRunStop } from './use-cron-run-stop'
+
+const cancelCronJobRun = vi.fn()
+const getCronJobRuns = vi.fn()
+const getCronJobs = vi.fn()
+
+vi.mock('@/hermes', async importOriginal => ({
+ ...(await importOriginal<typeof HermesApi>()),
+ cancelCronJobRun: (jobId: string) => cancelCronJobRun(jobId),
+ getCronJobRuns: (jobId: string) => getCronJobRuns(jobId),
+ getCronJobs: (profile?: string) => getCronJobs(profile)
+}))
+
+vi.mock('@/store/notifications', () => ({
+ notify: vi.fn(),
+ notifyError: vi.fn()
+}))
+
+const c = {
+ control: { failedStop: 'failed', finishedFirst: 'finished first', nothingToStop: 'nothing', stopped: 'Run cancelled' }
+} as unknown as Translations['cron']
+
+const running: CronJob = {
+ deliver: 'local',
+ enabled: true,
+ id: 'job-1',
+ latest_execution: { claimed_at: '2026-10-25T21:00:00Z', id: 'exec-1', status: 'running' },
+ name: 'Nightly digest',
+ prompt: 'Summarize',
+ schedule: { expr: '0 3 * * *', kind: 'cron' },
+ schedule_display: 'Every day at 03:00',
+ state: 'scheduled'
+} as CronJob
+
+beforeAll(() => {
+ HTMLElement.prototype.scrollIntoView ??= () => undefined
+ vi.stubGlobal('CSS', { escape: (value: string) => value })
+})
+
+beforeEach(() => {
+ setCronFocusJobId(null)
+ setChangeEventsAvailable(false)
+ getCronJobRuns.mockResolvedValue([])
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+ cleanup()
+ queryClient.clear()
+ invalidateCronJobsRequests()
+ setCronJobs([])
+ vi.clearAllMocks()
+})
+
+describe('cron job header while a run is live', () => {
+ it('offers Resume for a paused job whose last run is still going', async () => {
+ const pausedRunning = { ...running, enabled: false, state: 'paused' } as CronJob
+ setCronJobs([pausedRunning])
+ getCronJobs.mockResolvedValue([pausedRunning])
+ const { CronView } = await import('./index')
+
+ await act(async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <CronView onClose={vi.fn()} />
+ </QueryClientProvider>
+ )
+ })
+
+ // The click resumes the schedule (handlePauseResume reads the saved state), so the label must say so.
+ expect(await screen.findByRole('button', { name: 'Resume' })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Pause' })).toBeNull()
+ })
+})
+
+describe('useCronRunStop', () => {
+ it('lets a slow job-list refresh land instead of superseding it every poll', async () => {
+ vi.useFakeTimers()
+ const stopped = { ...running, latest_execution: { ...running.latest_execution!, status: 'cancelled' } } as CronJob
+ let inFlight = 0
+ let maxInFlight = 0
+ getCronJobs.mockImplementation(
+ () =>
+ new Promise(resolve => {
+ inFlight += 1
+ maxInFlight = Math.max(maxInFlight, inFlight)
+ setTimeout(() => {
+ inFlight -= 1
+ resolve([stopped])
+ }, 4000)
+ })
+ )
+
+ renderHook(() => useCronRunStop({ c, jobs: [running], profile: 'default', watch: true }))
+ await act(() => vi.advanceTimersByTimeAsync(12_000))
+
+ expect(maxInFlight).toBe(1)
+ expect($cronJobs.get()).toEqual([stopped])
+ })
+
+ it('does not announce a cancel when a connection switch wipes the job list', async () => {
+ cancelCronJobRun.mockReturnValue(new Promise<CronCancelResult>(() => undefined))
+
+ const { rerender, result } = renderHook(
+ ({ jobs }) => useCronRunStop({ c, jobs, profile: 'default', watch: false }),
+ {
+ initialProps: { jobs: [running] }
+ }
+ )
+
+ act(() => void result.current.stop(running))
+ expect(result.current.stoppingJobIds.has('job-1')).toBe(true)
+
+ // gateway-switch.ts clears the cache while the cancel request is still pending.
+ act(() => setCronJobs([]))
+ rerender({ jobs: [] })
+
+ expect(notify).not.toHaveBeenCalled()
+ expect(result.current.stoppingJobIds.has('job-1')).toBe(true)
+ })
+})
diff --git a/apps/desktop/src/app/cron/use-cron-run-stop.ts b/apps/desktop/src/app/cron/use-cron-run-stop.ts
index 8d287391529..df2db9f3d85 100644
--- a/apps/desktop/src/app/cron/use-cron-run-stop.ts
+++ b/apps/desktop/src/app/cron/use-cron-run-stop.ts
@@ -3,12 +3,13 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { cancelCronJobRun, type CronJob } from '@/hermes'
import type { Translations } from '@/i18n'
+import { getCronJobsSnapshotScope } from '@/store/cron'
import { $cronChangeTick } from '@/store/live-sync'
import { notify, notifyError } from '@/store/notifications'
-import { mutateAndRefreshCronJobs, refreshCronJobs } from './cron-actions'
+import { cronRequestScope, mutateAndRefreshCronJobs, refreshCronJobs } from './cron-actions'
import { jobTitle, truncateText } from './job-state'
-import { jobRunInFlight } from './run-control'
+import { stopOutcome } from './run-control'
// A cancel lands at the run's next cancel check (about a second); poll the job list that
// fast while a run is live or stopping so the button settles without a manual refresh.
@@ -27,14 +28,21 @@ export interface CronRunStop {
stoppingJobIds: ReadonlySet<string>
}
+interface PendingStop {
+ /** The execution the cancel targeted; '' until the endpoint names it. */
+ executionId: string
+ /** Backend scope (connection + profile) the Stop was sent to. */
+ scope: string
+ title: string
+}
+
/**
- * Stop for a cron job's live run: POST /cancel, then hold "Stopping…" until the job list
- * shows that attempt finished. A run that ends on its own first is reported as such, not
- * as cancelled.
+ * Stop for a cron job's live run: POST /cancel, then hold "Stopping…" until a job list from the
+ * same backend shows that attempt finished. A run that ends on its own first is reported as such,
+ * not as cancelled; a Stop left behind by a connection or profile switch is dropped silently.
*/
export function useCronRunStop({ c, jobs, profile, watch }: CronRunStopOptions): CronRunStop {
- // jobId → the execution the cancel targeted ('' until the endpoint names it) + its title.
- const stoppingRef = useRef(new Map<string, { executionId: string; title: string }>())
+ const stoppingRef = useRef(new Map<string, PendingStop>())
const [stoppingJobIds, setStoppingJobIds] = useState<ReadonlySet<string>>(() => new Set())
const cronChangeTick = useStore($cronChangeTick)
@@ -46,24 +54,35 @@ export function useCronRunStop({ c, jobs, profile, watch }: CronRunStopOptions):
return
}
+ const currentScope = cronRequestScope(profile)
+ // A list wiped by a connection switch is no evidence that any run ended.
+ const listScope = getCronJobsSnapshotScope()
let changed = false
- for (const [jobId, { executionId, title }] of stoppingRef.current) {
- const job = list.find(candidate => candidate.id === jobId)
+ for (const [jobId, { executionId, scope, title }] of stoppingRef.current) {
+ if (scope !== currentScope) {
+ stoppingRef.current.delete(jobId)
+ changed = true
- if (job && jobRunInFlight(job)) {
continue
}
- stoppingRef.current.delete(jobId)
- changed = true
+ const outcome =
+ listScope === scope
+ ? stopOutcome(
+ list.find(candidate => candidate.id === jobId),
+ executionId
+ )
+ : 'pending'
- const execution = job?.latest_execution
- // A removed job's run is stopped by the removal itself.
- const cancelled = !job || (execution?.status === 'cancelled' && (!executionId || execution.id === executionId))
+ if (outcome === 'pending') {
+ continue
+ }
+ stoppingRef.current.delete(jobId)
+ changed = true
notify(
- cancelled
+ outcome === 'cancelled'
? { kind: 'success', title: c.control.stopped, message: title }
: { kind: 'info', title: c.control.finishedFirst, message: title }
)
@@ -73,7 +92,7 @@ export function useCronRunStop({ c, jobs, profile, watch }: CronRunStopOptions):
publish()
}
},
- [c, publish]
+ [c, profile, publish]
)
// Another surface (the poll below, the sidebar, a cron.changed refresh) may publish the
@@ -87,13 +106,27 @@ export function useCronRunStop({ c, jobs, profile, watch }: CronRunStopOptions):
return
}
- const intervalId = window.setInterval(() => {
+ // One refresh at a time: each request supersedes the one before it, so polls overlapping on a
+ // slow backend would keep every reply stale and the page would never leave "Stopping…".
+ let timeoutId: number | undefined
+ let disposed = false
+
+ const poll = async () => {
if (document.visibilityState === 'visible') {
- void refreshCronJobs(profile)
+ await refreshCronJobs(profile)
}
- }, LIVE_RUN_POLL_MS)
- return () => window.clearInterval(intervalId)
+ if (!disposed) {
+ timeoutId = window.setTimeout(poll, LIVE_RUN_POLL_MS)
+ }
+ }
+
+ timeoutId = window.setTimeout(poll, LIVE_RUN_POLL_MS)
+
+ return () => {
+ disposed = true
+ window.clearTimeout(timeoutId)
+ }
}, [active, profile])
// A scheduler fire rewrites jobs.json (cron.changed): refresh so a run the user did not
@@ -111,8 +144,9 @@ export function useCronRunStop({ c, jobs, profile, watch }: CronRunStopOptions):
}
const title = truncateText(jobTitle(job), 60)
+ const scope = cronRequestScope(profile)
- stoppingRef.current.set(job.id, { executionId: '', title })
+ stoppingRef.current.set(job.id, { executionId: '', scope, title })
publish()
try {
@@ -126,8 +160,8 @@ export function useCronRunStop({ c, jobs, profile, watch }: CronRunStopOptions):
return
}
- if (value?.execution_id && stoppingRef.current.has(job.id)) {
- stoppingRef.current.set(job.id, { executionId: value.execution_id, title })
+ if (value?.execution_id && stoppingRef.current.get(job.id)?.scope === scope) {
+ stoppingRef.current.set(job.id, { executionId: value.execution_id, scope, title })
}
settle(refreshed)
diff --git a/apps/desktop/src/store/cron.ts b/apps/desktop/src/store/cron.ts
index b6df8cb0fc5..f24fe29cac9 100644
--- a/apps/desktop/src/store/cron.ts
+++ b/apps/desktop/src/store/cron.ts
@@ -20,6 +20,13 @@ export interface CronJobsScopeToken {
let cronJobsRequestGeneration = 0
let cronJobsRequestScope = ''
let cronJobsScopeGeneration = 0
+// The backend scope (connection + profile) the published list was fetched from; '' once a
+// connection switch wiped it. A cleared cache is not evidence about any backend's jobs.
+let cronJobsSnapshotScope = ''
+
+export function getCronJobsSnapshotScope(): string {
+ return cronJobsSnapshotScope
+}
function activateCronJobsScope(scope: string): void {
if (scope === cronJobsRequestScope) {
@@ -65,6 +72,7 @@ export function commitCronJobsRequest(request: CronJobsRequest, jobs: CronJob[])
// Consume the token so neither a duplicate completion nor any older request
// can publish after this authoritative snapshot.
cronJobsRequestGeneration += 1
+ cronJobsSnapshotScope = request.scope
$cronJobs.set(jobs)
return true
@@ -72,6 +80,7 @@ export function commitCronJobsRequest(request: CronJobsRequest, jobs: CronJob[])
export const setCronJobs = (jobs: CronJob[]) => {
cronJobsRequestGeneration += 1
+ cronJobsSnapshotScope = ''
$cronJobs.set(jobs)
}