Skip to content

The agent that grows with you

fix(cron): add reliable trigger feedback in Web and Desktop clients

Evgeniif9d64b9a9d8b
diff --git a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx
index 9fadcfbc424..30fb25bde1e 100644
--- a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx
+++ b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx
@@ -1,5 +1,6 @@
+import { createCronTriggerController, type CronTriggerController } from '@hermes/shared'
import { useStore } from '@nanostores/react'
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
import { ActionsContextMenu, type MenuKit, renderActionItem } from '@/components/ui/actions-menu'
@@ -72,7 +73,7 @@ interface SidebarCronJobsSectionProps {
// Open the full Cron page focused on this job (manage / full history).
onManageJob: (jobId: string) => void
// Fire the job now.
- onTriggerJob: (jobId: string) => void
+ onTriggerJob: (jobId: string) => Promise<void>
onToggle: () => void
open: boolean
}
@@ -92,6 +93,45 @@ export function SidebarCronJobsSection({
const [peekJobId, setPeekJobId] = useState<null | string>(null)
// Rows revealed so far; starts compact, grows in steps via "load more".
const [visibleCount, setVisibleCount] = useState(INITIAL_VISIBLE_JOBS)
+ const [triggeringJobIds, setTriggeringJobIds] = useState<ReadonlySet<string>>(() => new Set())
+ const triggerControllerRef = useRef<CronTriggerController | null>(null)
+
+ // eslint-disable-next-line no-restricted-syntax -- controller mount identity, not an atom mirror
+ useEffect(() => {
+ const controller = createCronTriggerController((jobId, running) => {
+ if (triggerControllerRef.current !== controller) {
+ return
+ }
+
+ setTriggeringJobIds(current => {
+ const next = new Set(current)
+
+ if (running) {
+ next.add(jobId)
+ } else {
+ next.delete(jobId)
+ }
+
+ return next
+ })
+ })
+
+ triggerControllerRef.current = controller
+
+ return () => {
+ triggerControllerRef.current = null
+ }
+ }, [])
+
+ const triggerJob = (jobId: string) => {
+ const controller = triggerControllerRef.current
+
+ if (!controller) {
+ return
+ }
+
+ void controller.run(jobId, () => onTriggerJob(jobId)).catch(() => undefined)
+ }
const visible = usePaneVisible()
@@ -153,6 +193,7 @@ export function SidebarCronJobsSection({
<SidebarGroupContent className="scrollbar-fade flex max-h-72 flex-col gap-px overflow-x-hidden overflow-y-auto overscroll-contain pb-1.75 compact:max-h-none compact:overflow-visible">
{shown.map(job => (
<CronJobSidebarRow
+ busy={triggeringJobIds.has(job.id)}
expanded={peekJobId === job.id}
job={job}
key={job.id}
@@ -160,7 +201,7 @@ export function SidebarCronJobsSection({
onManage={() => onManageJob(job.id)}
onOpenRun={onOpenRun}
onTogglePeek={() => setPeekJobId(prev => (prev === job.id ? null : job.id))}
- onTrigger={() => onTriggerJob(job.id)}
+ onTrigger={() => triggerJob(job.id)}
/>
))}
{hiddenCount > 0 && (
@@ -176,6 +217,7 @@ export function SidebarCronJobsSection({
}
function CronJobSidebarRow({
+ busy,
expanded,
job,
nowMs,
@@ -184,6 +226,7 @@ function CronJobSidebarRow({
onTogglePeek,
onTrigger
}: {
+ busy: boolean
expanded: boolean
job: CronJob
nowMs: number
@@ -298,11 +341,12 @@ function CronJobSidebarRow({
<Tip label={c.triggerNow}>
<button
aria-label={c.triggerNow}
- className="grid size-5 place-items-center rounded-sm text-(--ui-text-tertiary) hover:bg-(--ui-control-hover-background) hover:text-foreground"
+ className="grid size-5 place-items-center rounded-sm text-(--ui-text-tertiary) hover:bg-(--ui-control-hover-background) hover:text-foreground disabled:cursor-wait disabled:opacity-60"
+ disabled={busy}
onClick={onTrigger}
type="button"
>
- <Codicon name="zap" size="0.75rem" />
+ {busy ? <GlyphSpinner ariaLabel={c.triggerNow} className="text-[0.75rem]" /> : <Codicon name="zap" size="0.75rem" />}
</button>
</Tip>
<Tip label={c.manage}>
diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsx
index 6377cd75b8f..fc9d1f36091 100644
--- a/apps/desktop/src/app/chat/sidebar/index.tsx
+++ b/apps/desktop/src/app/chat/sidebar/index.tsx
@@ -284,7 +284,7 @@ interface ChatSidebarProps extends React.ComponentProps<typeof Sidebar> {
/** Create a brand-new session and open it as a tile on `dir`. */
onNewSessionSplit: (dir: SplitDir) => void
onManageCronJob: (jobId: string) => void
- onTriggerCronJob: (jobId: string) => void
+ onTriggerCronJob: (jobId: string) => Promise<void>
}
export function ChatSidebar({
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index b670d831455..ea819a09606 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -24,7 +24,7 @@ import { $newSessionTabAction, registerPaneCloser } from '@/components/pane-shel
import { FloatingPet } from '@/components/pet/floating-pet'
import { RemoteDisplayBanner } from '@/components/remote-display-banner'
import { emitGatewayEvent } from '@/contrib/events'
-import { getLatestSessionMessages, triggerCronJob } from '@/hermes'
+import { getLatestSessionMessages } from '@/hermes'
import { type ChatMessage, chatMessageText, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'
import { isMessagingSource } from '@/lib/session-source'
import { latestSessionTodos } from '@/lib/todos'
@@ -40,6 +40,7 @@ import {
$activeGatewayProfile,
$freshSessionRequest,
$profileScope,
+ ALL_PROFILES,
ensureGatewayProfile,
newSessionInProfile,
normalizeProfileKey,
@@ -73,6 +74,7 @@ import { closeWorkspaceTab } from '../chat/close-tab'
import { requestComposerInsert } from '../chat/composer/focus'
import { useComposerActions } from '../chat/hooks/use-composer-actions'
import { CommandPalette } from '../command-palette'
+import { triggerAndRefreshCronJobs } from '../cron/cron-actions'
import { useGatewayBoot } from '../gateway/hooks/use-gateway-boot'
import { useGatewayRequest } from '../gateway/hooks/use-gateway-request'
import { useKeybinds } from '../hooks/use-keybinds'
@@ -901,11 +903,10 @@ export function ContribWiring({ children }: { children: ReactNode }) {
onThreadMessagesChange: handleThreadMessagesChange,
onToggleSelectedPin: toggleSelectedPin,
onTranscribeAudio: transcribeVoiceAudio,
- onTriggerCronJob: jobId => {
- void triggerCronJob(jobId)
- .then(() => refreshCronJobs())
- .catch(() => undefined)
- },
+ onTriggerCronJob: jobId =>
+ triggerAndRefreshCronJobs(jobId, profileScope === ALL_PROFILES ? 'all' : profileScope)
+ .then(() => undefined)
+ .catch(() => undefined),
getGateway: () => gatewayRef.current,
openAgents,
openCommandCenterSection,
diff --git a/apps/desktop/src/app/cron/cron-actions.test.ts b/apps/desktop/src/app/cron/cron-actions.test.ts
new file mode 100644
index 00000000000..61e6dd1aa30
--- /dev/null
+++ b/apps/desktop/src/app/cron/cron-actions.test.ts
@@ -0,0 +1,187 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const getCronJobs = vi.fn()
+const triggerCronJob = vi.fn()
+
+vi.mock('@/hermes', () => ({
+ getCronJobs: (...args: unknown[]) => getCronJobs(...args),
+ triggerCronJob: (...args: unknown[]) => triggerCronJob(...args)
+}))
+
+import { beginCronJobsRequest } from '@/store/cron'
+
+import { mutateAndRefreshCronJobs, refreshCronJobs, triggerAndRefreshCronJobs } from './cron-actions'
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+
+ const promise = new Promise<T>(res => {
+ resolve = res
+ })
+
+ return { promise, resolve }
+}
+
+describe('triggerAndRefreshCronJobs', () => {
+ beforeEach(() => {
+ getCronJobs.mockReset()
+ triggerCronJob.mockReset()
+ })
+
+ it('replaces the local cache with the authoritative list after a trigger', async () => {
+ const authoritative = [{ id: 'recurring-job', state: 'scheduled' }]
+ triggerCronJob.mockResolvedValue({ id: 'deleted-one-shot', state: 'completed' })
+ getCronJobs.mockResolvedValue(authoritative)
+
+ const result = await triggerAndRefreshCronJobs('deleted-one-shot', 'work')
+
+ expect(triggerCronJob).toHaveBeenCalledWith('deleted-one-shot')
+ expect(getCronJobs).toHaveBeenCalledWith('work')
+ expect(result).toEqual({ jobs: authoritative, refreshError: null, stale: false })
+ })
+
+ it('reports refresh failure separately after a successful trigger', async () => {
+ const refreshError = new Error('refresh failed')
+ triggerCronJob.mockResolvedValue({ id: 'job-1', state: 'scheduled' })
+ getCronJobs.mockRejectedValue(refreshError)
+
+ const result = await triggerAndRefreshCronJobs('job-1', 'all')
+
+ expect(result).toEqual({ jobs: null, refreshError, stale: false })
+ })
+
+ it('still rejects when the trigger itself fails', async () => {
+ const triggerError = new Error('trigger failed')
+ triggerCronJob.mockRejectedValue(triggerError)
+
+ await expect(triggerAndRefreshCronJobs('job-1', 'all')).rejects.toBe(triggerError)
+ expect(getCronJobs).not.toHaveBeenCalled()
+ })
+
+ it('discards a trigger failure after the profile scope changes', async () => {
+ const trigger = deferred<never>()
+ triggerCronJob.mockReturnValue(trigger.promise)
+
+ const resultPromise = triggerAndRefreshCronJobs('job-1', 'work')
+ beginCronJobsRequest('personal')
+ trigger.resolve(Promise.reject(new Error('old profile failed')) as never)
+
+ await expect(resultPromise).resolves.toEqual({ jobs: null, refreshError: null, stale: true })
+ expect(getCronJobs).not.toHaveBeenCalled()
+ })
+
+ it('discards a trigger refresh after the profile scope changes', async () => {
+ const refresh = deferred<Array<{ id: string }>>()
+ triggerCronJob.mockResolvedValue({ id: 'job-1', state: 'scheduled' })
+ getCronJobs.mockReturnValue(refresh.promise)
+
+ const resultPromise = triggerAndRefreshCronJobs('job-1', 'work')
+ await triggerCronJob.mock.results[0]?.value
+
+ beginCronJobsRequest('personal')
+ refresh.resolve([{ id: 'work-job' }])
+
+ await expect(resultPromise).resolves.toEqual({ jobs: null, refreshError: null, stale: true })
+ })
+
+ it('discards an older ordinary refresh that completes after a trigger refresh', async () => {
+ const older = deferred<Array<{ id: string }>>()
+ const newer = deferred<Array<{ id: string }>>()
+ triggerCronJob.mockResolvedValue({ id: 'job-1', state: 'scheduled' })
+ getCronJobs.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise)
+
+ const olderPromise = refreshCronJobs('work')
+ const newerPromise = triggerAndRefreshCronJobs('job-1', 'work')
+ newer.resolve([{ id: 'newer' }])
+ older.resolve([{ id: 'older' }])
+
+ await expect(newerPromise).resolves.toEqual({
+ jobs: [{ id: 'newer' }],
+ refreshError: null,
+ stale: false
+ })
+ await expect(olderPromise).resolves.toEqual({ jobs: null, refreshError: null, stale: true })
+ })
+})
+
+describe('mutateAndRefreshCronJobs', () => {
+ beforeEach(() => {
+ getCronJobs.mockReset()
+ })
+
+ it('does not refresh the old profile after a successful mutation switches scope', async () => {
+ const mutation = deferred<{ id: string }>()
+ const resultPromise = mutateAndRefreshCronJobs('work', () => mutation.promise)
+
+ beginCronJobsRequest('personal')
+ mutation.resolve({ id: 'work-job' })
+
+ await expect(resultPromise).resolves.toEqual({
+ jobs: null,
+ refreshError: null,
+ stale: true,
+ value: null
+ })
+ expect(getCronJobs).not.toHaveBeenCalled()
+ })
+
+ it('suppresses a mutation error after the profile scope changes', async () => {
+ const mutation = deferred<never>()
+ const resultPromise = mutateAndRefreshCronJobs('work', () => mutation.promise)
+
+ beginCronJobsRequest('personal')
+ mutation.resolve(Promise.reject(new Error('old profile failed')) as never)
+
+ await expect(resultPromise).resolves.toEqual({
+ jobs: null,
+ refreshError: null,
+ stale: true,
+ value: null
+ })
+ })
+
+ it('allows overlapping same-profile mutations to authoritatively refresh', async () => {
+ const first = deferred<string>()
+ const second = deferred<string>()
+ getCronJobs
+ .mockResolvedValueOnce([{ id: 'after-second' }])
+ .mockResolvedValueOnce([{ id: 'after-both' }])
+
+ const firstResult = mutateAndRefreshCronJobs('work', () => first.promise)
+ const secondResult = mutateAndRefreshCronJobs('work', () => second.promise)
+
+ second.resolve('second')
+ await expect(secondResult).resolves.toMatchObject({ stale: false, value: 'second' })
+
+ first.resolve('first')
+ await expect(firstResult).resolves.toMatchObject({ stale: false, value: 'first' })
+ expect(getCronJobs).toHaveBeenCalledTimes(2)
+ })
+
+ it('preserves a successful mutation when a newer same-profile refresh supersedes its snapshot', async () => {
+ const mutation = deferred<string>()
+ const mutationRefresh = deferred<Array<{ id: string }>>()
+ const newerRefresh = deferred<Array<{ id: string }>>()
+ getCronJobs.mockReturnValueOnce(mutationRefresh.promise).mockReturnValueOnce(newerRefresh.promise)
+
+ const mutationResult = mutateAndRefreshCronJobs('work', () => mutation.promise)
+ mutation.resolve('created')
+ await vi.waitFor(() => expect(getCronJobs).toHaveBeenCalledTimes(1))
+
+ const newerResult = refreshCronJobs('work')
+ newerRefresh.resolve([{ id: 'newer' }])
+ await expect(newerResult).resolves.toEqual({
+ jobs: [{ id: 'newer' }],
+ refreshError: null,
+ stale: false
+ })
+
+ mutationRefresh.resolve([{ id: 'older' }])
+ await expect(mutationResult).resolves.toEqual({
+ jobs: null,
+ refreshError: null,
+ stale: false,
+ value: 'created'
+ })
+ })
+})
diff --git a/apps/desktop/src/app/cron/cron-actions.ts b/apps/desktop/src/app/cron/cron-actions.ts
new file mode 100644
index 00000000000..95cc07c63e9
--- /dev/null
+++ b/apps/desktop/src/app/cron/cron-actions.ts
@@ -0,0 +1,98 @@
+import { type CronJob, getCronJobs, triggerCronJob } from '@/hermes'
+import {
+ beginCronJobsAction,
+ beginCronJobsRequest,
+ commitCronJobsRequest,
+ type CronJobsRequest,
+ isCronJobsRequestCurrent,
+ isCronJobsScopeCurrent
+} from '@/store/cron'
+
+export interface CronTriggerRefreshResult {
+ jobs: CronJob[] | null
+ refreshError: unknown | null
+ stale: boolean
+}
+
+export interface CronMutationRefreshResult<T> extends CronTriggerRefreshResult {
+ value: T | null
+}
+
+async function refreshForGeneration(
+ profile: string,
+ request: CronJobsRequest
+): Promise<CronTriggerRefreshResult> {
+ try {
+ const jobs = await getCronJobs(profile)
+
+ if (!commitCronJobsRequest(request, jobs)) {
+ return { jobs: null, refreshError: null, stale: true }
+ }
+
+ return { jobs, refreshError: null, stale: false }
+ } catch (refreshError) {
+ if (!isCronJobsRequestCurrent(request)) {
+ return { jobs: null, refreshError: null, stale: true }
+ }
+
+ return { jobs: null, refreshError, stale: false }
+ }
+}
+
+export function refreshCronJobs(profile: string): Promise<CronTriggerRefreshResult> {
+ return refreshForGeneration(profile, beginCronJobsRequest(profile))
+}
+
+export async function mutateAndRefreshCronJobs<T>(
+ profile: string,
+ mutate: () => Promise<T>
+): Promise<CronMutationRefreshResult<T>> {
+ const scopeToken = beginCronJobsAction(profile)
+ let value: T
+
+ try {
+ value = await mutate()
+ } catch (mutationError) {
+ if (!isCronJobsScopeCurrent(scopeToken)) {
+ return { jobs: null, refreshError: null, stale: true, value: null }
+ }
+
+ throw mutationError
+ }
+
+ if (!isCronJobsScopeCurrent(scopeToken)) {
+ return { jobs: null, refreshError: null, stale: true, value: null }
+ }
+
+ const refreshed = await refreshCronJobs(profile)
+
+ if (!isCronJobsScopeCurrent(scopeToken)) {
+ return { jobs: null, refreshError: null, stale: true, value: null }
+ }
+
+ // A newer request in the same scope may supersede this refresh after the
+ // mutation itself has already succeeded. Preserve the mutation result so
+ // callers can settle dialogs/toasts without publishing the older snapshot.
+ if (refreshed.stale) {
+ return { jobs: null, refreshError: null, stale: false, value }
+ }
+
+ return { ...refreshed, value }
+}
+
+/**
+ * Trigger a job synchronously, then replace the local view from the backend.
+ * A completed one-shot may have been deleted, so the trigger response alone is
+ * not an authoritative list update. Refresh failure is reported separately:
+ * the trigger already succeeded and must not be shown as failed.
+ */
+export async function triggerAndRefreshCronJobs(
+ jobId: string,
+ profile: 'all' | string
+): Promise<CronTriggerRefreshResult> {
+ const { value: _value, ...result } = await mutateAndRefreshCronJobs(profile, () =>
+ triggerCronJob(jobId)
+ )
+
+ return result
+}
\ No newline at end of file
diff --git a/apps/desktop/src/app/cron/index.tsx b/apps/desktop/src/app/cron/index.tsx
index 616a9b956dd..1b6e6ab1566 100644
--- a/apps/desktop/src/app/cron/index.tsx
+++ b/apps/desktop/src/app/cron/index.tsx
@@ -1,3 +1,4 @@
+import { createCronTriggerController, type CronTriggerController } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useQuery } from '@tanstack/react-query'
import type * as React from 'react'
@@ -36,19 +37,17 @@ import {
getAutomationBlueprints,
getCronDeliveryTargets,
getCronJobRuns,
- getCronJobs,
instantiateAutomationBlueprint,
pauseCronJob,
resumeCronJob,
type SessionInfo,
- triggerCronJob,
updateCronJob
} from '@/hermes'
import { type Translations, useI18n } from '@/i18n'
import { AlertTriangle } from '@/lib/icons'
import { requestModelOptions } from '@/lib/model-options'
import { asText } from '@/lib/text'
-import { $cronFocusJobId, $cronJobs, setCronFocusJobId, setCronJobs, updateCronJobs } from '@/store/cron'
+import { $cronFocusJobId, $cronJobs, invalidateCronJobsRequests, setCronFocusJobId } from '@/store/cron'
import { $changeEventsAvailable, $cronChangeTick } from '@/store/live-sync'
import { notify, notifyError } from '@/store/notifications'
import { $profileScope, ALL_PROFILES } from '@/store/profile'
@@ -74,6 +73,7 @@ import {
import type { SetStatusbarItemGroup } from '../shell/statusbar-controls'
import { BlueprintSlotControl, blueprintSlotHelp, cleanBlueprintFieldError, initialBlueprintValues } from './blueprints'
+import { mutateAndRefreshCronJobs, refreshCronJobs, triggerAndRefreshCronJobs } from './cron-actions'
import {
cronEditorUpdates,
jobIsScriptOnly,
@@ -93,6 +93,10 @@ const MODEL_DEFAULT_VALUE = '__default__'
// blueprint key. Blueprint keys never collide with this sentinel.
const CUSTOM_TEMPLATE = 'custom'
+function cronProfileForScope(scope: string): string {
+ return scope === ALL_PROFILES ? 'all' : scope
+}
+
const SCHEDULE_OPTIONS: ReadonlyArray<ScheduleOption> = [
{ expr: '0 9 * * *', value: 'daily' },
{ expr: '0 9 * * 1-5', value: 'weekdays' },
@@ -299,7 +303,37 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
const jobs = useStore($cronJobs)
const [loading, setLoading] = useState(jobs.length === 0)
const [query, setQuery] = useState('')
- const [busyJobId, setBusyJobId] = useState<null | string>(null)
+ const [busyJobTokens, setBusyJobTokens] = useState<ReadonlyMap<string, symbol>>(() => new Map())
+ const [triggeringJobKeys, setTriggeringJobKeys] = useState<ReadonlySet<string>>(() => new Set())
+ const triggerControllerRef = useRef<CronTriggerController | null>(null)
+
+ // eslint-disable-next-line no-restricted-syntax -- controller mount identity, not an atom mirror
+ useEffect(() => {
+ const controller = createCronTriggerController((key, running) => {
+ if (triggerControllerRef.current !== controller) {
+ return
+ }
+
+ setTriggeringJobKeys(current => {
+ const next = new Set(current)
+
+ if (running) {
+ next.add(key)
+ } else {
+ next.delete(key)
+ }
+
+ return next
+ })
+ })
+
+ triggerControllerRef.current = controller
+
+ return () => {
+ triggerControllerRef.current = null
+ }
+ }, [])
+
// Master/detail: the job whose schedule + run history fill the right pane.
const [selectedJobId, setSelectedJobId] = useState<null | string>(null)
// Set when a job is opened from the sidebar so we scroll it into view once the
@@ -315,21 +349,30 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
// default — scope the fetch to the sidebar's profile scope so this overlay
// and the sidebar (which share the $cronJobs atom) agree on what's shown.
const profileScope = useStore($profileScope)
+ const profile = cronProfileForScope(profileScope)
const refresh = useCallback(async () => {
- try {
- setCronJobs(await getCronJobs(profileScope === ALL_PROFILES ? 'all' : profileScope))
- } catch (err) {
- notifyError(err, c.failedLoad)
- } finally {
- setLoading(false)
+ const { refreshError, stale } = await refreshCronJobs(profile)
+
+ if (stale) {
+ return
}
- }, [c, profileScope])
+
+ if (refreshError) {
+ notifyError(refreshError, c.failedLoad)
+ }
+
+ setLoading(false)
+ }, [c, profile])
useRefreshHotkey(refresh)
useEffect(() => {
void refresh()
+ // Fence the previous profile's request before the next profile effect, and
+ // fence every pending completion when the overlay unmounts.
+
+ return () => invalidateCronJobsRequests()
}, [refresh])
// Sidebar → "open this job": resolve the focus id (or name) to a job, select
@@ -395,13 +438,46 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
const totalCount = jobs.length
+ function beginJobBusy(jobId: string): symbol {
+ const token = Symbol(jobId)
+
+ setBusyJobTokens(current => new Map(current).set(jobId, token))
+
+ return token
+ }
+
+ function endJobBusy(jobId: string, token: symbol): void {
+ setBusyJobTokens(current => {
+ if (current.get(jobId) !== token) {
+ return current
+ }
+
+ const next = new Map(current)
+
+ next.delete(jobId)
+
+ return next
+ })
+ }
+
async function handlePauseResume(job: CronJob) {
- setBusyJobId(job.id)
+ const busyToken = beginJobBusy(job.id)
try {
const isPaused = jobState(job) === 'paused'
- const updated = isPaused ? await resumeCronJob(job.id) : await pauseCronJob(job.id)
- updateCronJobs(rows => rows.map(row => (row.id === job.id ? updated : row)))
+
+ const { refreshError, stale } = await mutateAndRefreshCronJobs(profile, () =>
+ isPaused ? resumeCronJob(job.id) : pauseCronJob(job.id)
+ )
+
+ if (stale) {
+ return
+ }
+
+ if (refreshError) {
+ notifyError(refreshError, c.failedLoad)
+ }
+
notify({
kind: 'success',
title: isPaused ? c.resumed : c.paused,
@@ -410,21 +486,50 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
} catch (err) {
notifyError(err, c.failedUpdate)
} finally {
- setBusyJobId(null)
+ endJobBusy(job.id, busyToken)
}
}
async function handleTrigger(job: CronJob) {
- setBusyJobId(job.id)
+ const viewProfile = profile
+ const key = `${viewProfile}:${job.id}`
+ const controller = triggerControllerRef.current
+
+ if (!controller) {
+ return
+ }
try {
- const updated = await triggerCronJob(job.id)
- updateCronJobs(rows => rows.map(row => (row.id === job.id ? updated : row)))
+ const run = await controller.run(
+ key,
+ () => triggerAndRefreshCronJobs(job.id, viewProfile),
+ () => notify({ kind: 'info', title: c.triggerNow, message: truncate(jobTitle(job), 60) })
+ )
+
+ if (
+ triggerControllerRef.current !== controller ||
+ cronProfileForScope($profileScope.get()) !== viewProfile ||
+ !run.started ||
+ !run.value
+ ) {
+ return
+ }
+
+ const { refreshError, stale } = run.value
+
+ if (stale) {
+ return
+ }
+
+ if (refreshError) {
+ notifyError(refreshError, c.failedLoad)
+ }
+
notify({ kind: 'success', title: c.triggered, message: truncate(jobTitle(job), 60) })
} catch (err) {
- notifyError(err, c.failedTrigger)
- } finally {
- setBusyJobId(null)
+ if (triggerControllerRef.current === controller && cronProfileForScope($profileScope.get()) === viewProfile) {
+ notifyError(err, c.failedTrigger)
+ }
}
}
@@ -436,8 +541,18 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
setDeleting(true)
try {
- await deleteCronJob(pendingDelete.id)
- updateCronJobs(rows => rows.filter(row => row.id !== pendingDelete.id))
+ const { refreshError, stale } = await mutateAndRefreshCronJobs(profile, () =>
+ deleteCronJob(pendingDelete.id)
+ )
+
+ if (stale) {
+ return
+ }
+
+ if (refreshError) {
+ notifyError(refreshError, c.failedLoad)
+ }
+
notify({ kind: 'success', title: c.deleted, message: truncate(jobTitle(pendingDelete), 60) })
setPendingDelete(null)
} catch (err) {
@@ -449,22 +564,40 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
async function handleEditorSave(values: EditorValues) {
if (editor.mode === 'create') {
- const created = await createCronJob({
- prompt: values.prompt,
- schedule: values.schedule,
- name: values.name || undefined,
- deliver: values.deliver || DEFAULT_DELIVER,
- ...(values.model.trim() ? { model: values.model.trim(), provider: values.provider.trim() || undefined } : {})
- })
+ const { value: created, refreshError, stale } = await mutateAndRefreshCronJobs(profile, () =>
+ createCronJob({
+ prompt: values.prompt,
+ schedule: values.schedule,
+ name: values.name || undefined,
+ deliver: values.deliver || DEFAULT_DELIVER,
+ ...(values.model.trim() ? { model: values.model.trim(), provider: values.provider.trim() || undefined } : {})
+ })
+ )
+
+ if (stale || !created) {
+ return
+ }
+
+ if (refreshError) {
+ notifyError(refreshError, c.failedLoad)
+ }
- updateCronJobs(rows => [...rows, created])
notify({ kind: 'success', title: c.created, message: truncate(jobTitle(created), 60) })
} else if (editor.mode === 'edit') {
const scriptOnlyJob = jobIsScriptOnly(editor.job)
- const updated = await updateCronJob(editor.job.id, cronEditorUpdates(values, { scriptOnlyJob }))
+ const { value: updated, refreshError, stale } = await mutateAndRefreshCronJobs(profile, () =>
+ updateCronJob(editor.job.id, cronEditorUpdates(values, { scriptOnlyJob }))
+ )
+
+ if (stale || !updated) {
+ return
+ }
+
+ if (refreshError) {
+ notifyError(refreshError, c.failedLoad)
+ }
- updateCronJobs(rows => rows.map(row => (row.id === updated.id ? updated : row)))
notify({ kind: 'success', title: c.updated, message: truncate(jobTitle(updated), 60) })
}
@@ -477,14 +610,20 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
// real per-profile job, and "all" is not a writable target — collapse it to
// 'default', matching the manual create path in handleEditorSave.
async function handleBlueprintCreate(blueprint: AutomationBlueprint, values: Record<string, string>) {
- const profile = profileScope === ALL_PROFILES ? 'default' : profileScope
- const job = await instantiateAutomationBlueprint({ blueprint: blueprint.key, values }, profile)
+ const writableProfile = profileScope === ALL_PROFILES ? 'default' : profileScope
- updateCronJobs(rows => {
- const rest = rows.filter(row => row.id !== job.id)
+ const { value: job, refreshError, stale } = await mutateAndRefreshCronJobs(profile, () =>
+ instantiateAutomationBlueprint({ blueprint: blueprint.key, values }, writableProfile)
+ )
+
+ if (stale || !job) {
+ return
+ }
+
+ if (refreshError) {
+ notifyError(refreshError, c.failedLoad)
+ }
- return [...rest, job]
- })
notify({ kind: 'success', title: c.blueprints.scheduled, message: asText(job.schedule_display) || blueprint.title })
setEditor({ mode: 'closed' })
}
@@ -555,7 +694,7 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
{selectedJob ? (
<CronJobDetail
- busy={busyJobId === selectedJob.id}
+ busy={busyJobTokens.has(selectedJob.id) || triggeringJobKeys.has(`${profile}:${selectedJob.id}`)}
c={c}
job={selectedJob}
onOpenSession={onOpenSession}
diff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts b/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
index 8e26f770d21..bad975a5b31 100644
--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef } from 'react'
-import { getCronJobs, listAllProfileSessions, listSidebarSessions, type SessionInfo } from '@/hermes'
+import { listAllProfileSessions, listSidebarSessions, type SessionInfo } from '@/hermes'
import { sameCronSignature } from '@/lib/session-signatures'
import {
isMessagingSource,
@@ -8,7 +8,6 @@ import {
MESSAGING_SESSION_SOURCE_IDS,
normalizeSessionSource
} from '@/lib/session-source'
-import { setCronJobs } from '@/store/cron'
import {
$pinnedSessionIds,
$sessionsLimit,
@@ -38,6 +37,8 @@ import {
} from '@/store/session'
import { $workingSessionIds, getRecentlySettledSessionIds } from '@/store/session-states'
+import { refreshCronJobs as refreshCronJobsStore } from '../../cron/cron-actions'
+
// The recents list is local-only: cron rows have their own section, kanban
// dispatcher workers are read on the board, and each messaging platform
// (telegram, discord, …) is fetched separately into its own self-managed
@@ -139,9 +140,7 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
// own jobs; ALL_PROFILES keeps the unified view.
const refreshCronJobs = useCallback(async () => {
try {
- const jobs = await getCronJobs(profileScope === ALL_PROFILES ? 'all' : profileScope)
-
- setCronJobs(jobs)
+ await refreshCronJobsStore(profileScope === ALL_PROFILES ? 'all' : profileScope)
} catch {
// Non-fatal: the cron section just keeps its last-known jobs.
}
diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.ts
index dff0379e103..da39116d06e 100644
--- a/apps/desktop/src/hermes.test.ts
+++ b/apps/desktop/src/hermes.test.ts
@@ -22,7 +22,8 @@ import {
resetSidebarBatchCapability,
setApiRequestProfile,
speakText,
- transcribeAudio
+ transcribeAudio,
+ triggerCronJob
} from './hermes'
import { refreshActiveProfile } from './store/profile'
@@ -310,6 +311,21 @@ describe('Hermes REST helpers', () => {
}
})
+ it('waits for synchronous cron triggers as a long-running operation', async () => {
+ api.mockResolvedValue({ id: 'job-1' })
+
+ await triggerCronJob('job-1')
+
+ const request = api.mock.calls[0]?.[0]
+ expect(request).toEqual(
+ expect.objectContaining({
+ path: '/api/cron/jobs/job-1/trigger',
+ method: 'POST'
+ })
+ )
+ expect(request.timeoutMs).toBeGreaterThanOrEqual(60 * 60 * 1000)
+ })
+
it('keeps the liveness poll on the short default so a dead backend fails fast', async () => {
api.mockResolvedValue({})
api.mockClear()
diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.ts
index d19b958603c..b747bffa749 100644
--- a/apps/desktop/src/hermes.ts
+++ b/apps/desktop/src/hermes.ts
@@ -86,6 +86,11 @@ import type {
export const STARTUP_REQUEST_TIMEOUT_MS = 60_000
const DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS = 30_000
const SESSION_LIST_REQUEST_TIMEOUT_MS = 60_000
+// The cron trigger endpoint intentionally waits for the whole job so its
+// response reflects the persisted execution result. Agent jobs can run far
+// longer than the Electron fetch default; keep this override local to the one
+// synchronous long-operation endpoint rather than weakening all API timeouts.
+export const CRON_TRIGGER_REQUEST_TIMEOUT_MS = 24 * 60 * 60 * 1000
// prompt.submit is effectively fire-and-forget: turn completion is signaled by
// stream / message.complete events, NOT by the RPC return. A long turn (MoA
// presets running references + aggregator in series, deep reasoning, large tool
@@ -1487,7 +1492,8 @@ export function triggerCronJob(jobId: string): Promise<CronJob> {
return window.hermesDesktop.api<CronJob>({
...profileScoped(),
path: `/api/cron/jobs/${encodeURIComponent(jobId)}/trigger`,
- method: 'POST'
+ method: 'POST',
+ timeoutMs: CRON_TRIGGER_REQUEST_TIMEOUT_MS
})
}
diff --git a/apps/desktop/src/store/cron.test.ts b/apps/desktop/src/store/cron.test.ts
new file mode 100644
index 00000000000..e4db02e1f5b
--- /dev/null
+++ b/apps/desktop/src/store/cron.test.ts
@@ -0,0 +1,45 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import {
+ $cronJobs,
+ beginCronJobsRequest,
+ commitCronJobsRequest,
+ setCronJobs,
+ updateCronJobs
+} from './cron'
+
+const oldJob = { id: 'old' } as never
+const newJob = { id: 'new' } as never
+
+describe('cron jobs request fencing', () => {
+ beforeEach(() => {
+ setCronJobs([])
+ })
+
+ it('rejects an older refresh after a newer refresh commits', () => {
+ const older = beginCronJobsRequest('all')
+ const newer = beginCronJobsRequest('all')
+
+ expect(commitCronJobsRequest(newer, [newJob])).toBe(true)
+ expect(commitCronJobsRequest(older, [oldJob])).toBe(false)
+ expect($cronJobs.get()).toEqual([newJob])
+ })
+
+ it('rejects a refresh from the previous profile scope', () => {
+ const work = beginCronJobsRequest('work')
+
+ beginCronJobsRequest('personal')
+
+ expect(commitCronJobsRequest(work, [oldJob])).toBe(false)
+ expect($cronJobs.get()).toEqual([])
+ })
+
+ it('rejects an in-flight poll after a local mutation', () => {
+ const poll = beginCronJobsRequest('all')
+
+ updateCronJobs(() => [newJob])
+
+ expect(commitCronJobsRequest(poll, [oldJob])).toBe(false)
+ expect($cronJobs.get()).toEqual([newJob])
+ })
+})
diff --git a/apps/desktop/src/store/cron.ts b/apps/desktop/src/store/cron.ts
index f017f60dc12..b6df8cb0fc5 100644
--- a/apps/desktop/src/store/cron.ts
+++ b/apps/desktop/src/store/cron.ts
@@ -6,11 +6,81 @@ import type { CronJob } from '@/types/hermes'
// the job — schedule, state, live next-run countdown — makes the job the
// first-class entity; its runs (sessions) resolve under it in the cron detail.
export const $cronJobs = atom<CronJob[]>([])
-export const setCronJobs = (jobs: CronJob[]) => $cronJobs.set(jobs)
+
+export interface CronJobsRequest {
+ generation: number
+ scope: string
+}
+
+export interface CronJobsScopeToken {
+ generation: number
+ scope: string
+}
+
+let cronJobsRequestGeneration = 0
+let cronJobsRequestScope = ''
+let cronJobsScopeGeneration = 0
+
+function activateCronJobsScope(scope: string): void {
+ if (scope === cronJobsRequestScope) {
+ return
+ }
+
+ cronJobsRequestScope = scope
+ cronJobsRequestGeneration += 1
+ cronJobsScopeGeneration += 1
+}
+
+export function beginCronJobsRequest(scope: string): CronJobsRequest {
+ activateCronJobsScope(scope)
+ cronJobsRequestGeneration += 1
+
+ return { generation: cronJobsRequestGeneration, scope }
+}
+
+export function beginCronJobsAction(scope: string): CronJobsScopeToken {
+ activateCronJobsScope(scope)
+
+ return { generation: cronJobsScopeGeneration, scope }
+}
+
+export function isCronJobsScopeCurrent(token: CronJobsScopeToken): boolean {
+ return token.scope === cronJobsRequestScope && token.generation === cronJobsScopeGeneration
+}
+
+export function isCronJobsRequestCurrent(request: CronJobsRequest): boolean {
+ return request.scope === cronJobsRequestScope && request.generation === cronJobsRequestGeneration
+}
+
+export function invalidateCronJobsRequests(): void {
+ cronJobsRequestGeneration += 1
+ cronJobsScopeGeneration += 1
+}
+
+export function commitCronJobsRequest(request: CronJobsRequest, jobs: CronJob[]): boolean {
+ if (!isCronJobsRequestCurrent(request)) {
+ return false
+ }
+
+ // Consume the token so neither a duplicate completion nor any older request
+ // can publish after this authoritative snapshot.
+ cronJobsRequestGeneration += 1
+ $cronJobs.set(jobs)
+
+ return true
+}
+
+export const setCronJobs = (jobs: CronJob[]) => {
+ cronJobsRequestGeneration += 1
+ $cronJobs.set(jobs)
+}
// In-place edit so the cron overlay's mutations (create/edit/delete/pause/…)
// land in the same atom the sidebar renders — no stale list until the next poll.
-export const updateCronJobs = (fn: (jobs: CronJob[]) => CronJob[]) => $cronJobs.set(fn($cronJobs.get()))
+export const updateCronJobs = (fn: (jobs: CronJob[]) => CronJob[]) => {
+ cronJobsRequestGeneration += 1
+ $cronJobs.set(fn($cronJobs.get()))
+}
// One-shot focus target: clicking "Manage" on a job sets this, then opens the
// cron overlay, which reads it once to select + scroll to that job. Cleared
diff --git a/apps/shared/src/cron-trigger-controller.ts b/apps/shared/src/cron-trigger-controller.ts
new file mode 100644
index 00000000000..032231bd38d
--- /dev/null
+++ b/apps/shared/src/cron-trigger-controller.ts
@@ -0,0 +1,40 @@
+export interface CronTriggerRunResult<T> {
+ started: boolean
+ value: T | null
+}
+
+export interface CronTriggerController {
+ isRunning(key: string): boolean
+ run<T>(key: string, action: () => Promise<T>, onStarted?: () => void): Promise<CronTriggerRunResult<T>>
+}
+
+// This is an interaction guard for one mounted UI surface. Cross-window and
+// cross-process exclusion remains the backend's responsibility via its durable
+// cron claim; a renderer-local Set must never be treated as the execution lock.
+export function createCronTriggerController(
+ onRunningChange: (key: string, running: boolean) => void = () => undefined
+): CronTriggerController {
+ const running = new Set<string>()
+
+ return {
+ isRunning: key => running.has(key),
+ async run<T>(key: string, action: () => Promise<T>, onStarted?: () => void) {
+ if (running.has(key)) {
+ return { started: false, value: null }
+ }
+
+ running.add(key)
+
+ try {
+ onRunningChange(key, true)
+
+ onStarted?.()
+
+ return { started: true, value: await action() }
+ } finally {
+ running.delete(key)
+ onRunningChange(key, false)
+ }
+ }
+ }
+}
diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.ts
index 391a3715bd2..8a173429613 100644
--- a/apps/shared/src/index.ts
+++ b/apps/shared/src/index.ts
@@ -34,6 +34,11 @@ export {
type SettlementDeps,
type SettlementOutcome
} from './charge-settlement'
+export {
+ createCronTriggerController,
+ type CronTriggerController,
+ type CronTriggerRunResult
+} from './cron-trigger-controller'
export {
type ConnectionState,
type GatewayClientOptions,
diff --git a/web/src/lib/cron-trigger-controller.test.ts b/web/src/lib/cron-trigger-controller.test.ts
new file mode 100644
index 00000000000..2b527eb17d9
--- /dev/null
+++ b/web/src/lib/cron-trigger-controller.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createCronTriggerController } from "@hermes/shared";
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+
+ return { promise, reject, resolve };
+}
+
+describe("createCronTriggerController", () => {
+ it("announces immediately and coalesces the same job while it is running", async () => {
+ const request = deferred<string>();
+ const order: string[] = [];
+ const action = vi.fn(() => {
+ order.push("action");
+ return request.promise;
+ });
+ const onStarted = vi.fn(() => order.push("started"));
+ const onRunningChange = vi.fn();
+ const controller = createCronTriggerController(onRunningChange);
+
+ const first = controller.run("profile-a:job-1", action, onStarted);
+ const duplicate = await controller.run("profile-a:job-1", action, onStarted);
+
+ expect(action).toHaveBeenCalledTimes(1);
+ expect(onStarted).toHaveBeenCalledTimes(1);
+ expect(order).toEqual(["started", "action"]);
+ expect(onRunningChange).toHaveBeenNthCalledWith(1, "profile-a:job-1", true);
+ expect(duplicate).toEqual({ started: false, value: null });
+
+ request.resolve("done");
+ await expect(first).resolves.toEqual({ started: true, value: "done" });
+ expect(onRunningChange).toHaveBeenLastCalledWith("profile-a:job-1", false);
+ });
+
+ it("releases the job after failure so a retry can start", async () => {
+ const request = deferred<void>();
+ const controller = createCronTriggerController();
+
+ const failed = controller.run("job-1", () => request.promise);
+ request.reject(new Error("failed"));
+
+ await expect(failed).rejects.toThrow("failed");
+ await expect(controller.run("job-1", async () => "retried")).resolves.toEqual({
+ started: true,
+ value: "retried",
+ });
+ });
+
+ it("releases the job when the immediate feedback callback fails", async () => {
+ const controller = createCronTriggerController();
+
+ await expect(
+ controller.run("job-1", async () => "not-called", () => {
+ throw new Error("toast failed");
+ }),
+ ).rejects.toThrow("toast failed");
+
+ await expect(controller.run("job-1", async () => "retried")).resolves.toEqual({
+ started: true,
+ value: "retried",
+ });
+ });
+
+ it("allows the same job id in different profiles to run concurrently", async () => {
+ const defaultRequest = deferred<string>();
+ const workRequest = deferred<string>();
+ const defaultAction = vi.fn(() => defaultRequest.promise);
+ const workAction = vi.fn(() => workRequest.promise);
+ const controller = createCronTriggerController();
+
+ const defaultRun = controller.run("default:job-1", defaultAction);
+ const workRun = controller.run("work:job-1", workAction);
+
+ expect(defaultAction).toHaveBeenCalledTimes(1);
+ expect(workAction).toHaveBeenCalledTimes(1);
+
+ defaultRequest.resolve("default");
+ workRequest.resolve("work");
+
+ await expect(defaultRun).resolves.toEqual({ started: true, value: "default" });
+ await expect(workRun).resolves.toEqual({ started: true, value: "work" });
+ });
+
+ it("releases the job when the running-state callback fails", async () => {
+ const controller = createCronTriggerController((_key, running) => {
+ if (running) throw new Error("state callback failed");
+ });
+
+ await expect(controller.run("job-1", async () => "not-called")).rejects.toThrow(
+ "state callback failed",
+ );
+ expect(controller.isRunning("job-1")).toBe(false);
+ });
+
+ it("releases the job before the stopped-state callback runs", async () => {
+ const action = vi.fn(async () => "done");
+ const controller = createCronTriggerController((_key, running) => {
+ if (!running) throw new Error("stopped callback failed");
+ });
+
+ await expect(controller.run("job-1", action)).rejects.toThrow("stopped callback failed");
+ expect(controller.isRunning("job-1")).toBe(false);
+
+ await expect(controller.run("job-1", action)).rejects.toThrow("stopped callback failed");
+ expect(action).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/web/src/pages/CronPage.tsx b/web/src/pages/CronPage.tsx
index 2f55680fb5c..8d7b81ae7c1 100644
--- a/web/src/pages/CronPage.tsx
+++ b/web/src/pages/CronPage.tsx
@@ -1,4 +1,8 @@
-import { useCallback, useEffect, useLayoutEffect, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
+import {
+ type CronTriggerController,
+ createCronTriggerController,
+} from "@hermes/shared";
import { Clock, Pause, Pencil, Play, Trash2, X, Zap } from "lucide-react";
import { Badge } from "@nous-research/ui/ui/components/badge";
import { Button } from "@nous-research/ui/ui/components/button";
@@ -510,6 +514,27 @@ const STATUS_TONE: Record<string, "success" | "warning" | "destructive"> = {
export default function CronPage() {
const [jobs, setJobs] = useState<CronJob[]>([]);
+ const [triggeringJobKeys, setTriggeringJobKeys] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ const triggerControllerRef = useRef<CronTriggerController | null>(null);
+
+ useEffect(() => {
+ const controller = createCronTriggerController((key, running) => {
+ if (triggerControllerRef.current !== controller) return;
+ setTriggeringJobKeys((current) => {
+ const next = new Set(current);
+ if (running) next.add(key);
+ else next.delete(key);
+ return next;
+ });
+ });
+ triggerControllerRef.current = controller;
+
+ return () => {
+ triggerControllerRef.current = null;
+ };
+ }, []);
const [profiles, setProfiles] = useState<ProfileInfo[]>([]);
const [selectedProfile, setSelectedProfile] = useState("all");
const [view, setView] = useState<"jobs" | "blueprints">("jobs");
@@ -576,13 +601,38 @@ export default function CronPage() {
setEditForm(editorFormFromJob(job));
}, []);
- const loadJobs = useCallback(() => {
+ const selectedProfileRef = useRef(selectedProfile);
+ const jobsRequestGenerationRef = useRef(0);
+ const jobsActiveRef = useRef(false);
+
+ const loadJobs = useCallback((profile: string) => {
+ if (!jobsActiveRef.current || selectedProfileRef.current !== profile) return;
+
+ const generation = ++jobsRequestGenerationRef.current;
+
api
- .getCronJobs(selectedProfile)
- .then(setJobs)
- .catch(() => showToast(t.common.loading, "error"))
- .finally(() => setLoading(false));
- }, [selectedProfile, showToast, t.common.loading]);
+ .getCronJobs(profile)
+ .then((nextJobs) => {
+ if (
+ jobsRequestGenerationRef.current === generation &&
+ selectedProfileRef.current === profile
+ ) setJobs(nextJobs);
+ })
+ .catch(() => {
+ if (
+ jobsRequestGenerationRef.current === generation &&
+ selectedProfileRef.current === profile
+ ) {
+ showToast(t.common.loading, "error");
+ }
+ })
+ .finally(() => {
+ if (
+ jobsRequestGenerationRef.current === generation &&
+ selectedProfileRef.current === profile
+ ) setLoading(false);
+ });
+ }, [showToast, t.common.loading]);
useEffect(() => {
api
@@ -604,8 +654,15 @@ export default function CronPage() {
}, []);
useEffect(() => {
- loadJobs();
- }, [loadJobs]);
+ jobsActiveRef.current = true;
+ selectedProfileRef.current = selectedProfile;
+ loadJobs(selectedProfile);
+
+ return () => {
+ jobsActiveRef.current = false;
+ jobsRequestGenerationRef.current += 1;
+ };
+ }, [loadJobs, selectedProfile]);
// Load resources from the profile the create/edit form actually targets.
// Pass "default" explicitly so the global dashboard profile switch cannot
@@ -646,7 +703,7 @@ export default function CronPage() {
showToast(t.common.create + " ✓", "success");
setCreateForm(emptyCronJobForm());
setCreateModalOpen(false);
- loadJobs();
+ loadJobs(selectedProfile);
} catch (e) {
showToast(`${t.config.failedToSave}: ${e}`, "error");
} finally {
@@ -677,7 +734,7 @@ export default function CronPage() {
);
showToast("Saved changes ✓", "success");
setEditJob(null);
- loadJobs();
+ loadJobs(selectedProfile);
} catch (e) {
showToast(`${t.config.failedToSave}: ${e}`, "error");
} finally {
@@ -702,22 +759,45 @@ export default function CronPage() {
"success",
);
}
- loadJobs();
+ loadJobs(selectedProfile);
} catch (e) {
showToast(`${t.status.error}: ${e}`, "error");
}
};
const handleTrigger = async (job: CronJob) => {
+ const jobKey = getJobKey(job);
+ const label = `${t.cron.triggerNow}: "${truncateText(getJobTitle(job), 30)}"`;
+ const viewProfile = selectedProfile;
+ const controller = triggerControllerRef.current;
+
+ if (!controller) return;
+
try {
- await api.triggerCronJob(job.id, getJobProfile(job));
- showToast(
- `${t.cron.triggerNow}: "${truncateText(getJobTitle(job), 30)}"`,
- "success",
+ // No pre-request toast: the controller's running state already gives
+ // immediate in-progress feedback (disabled + spinning action), and a
+ // success-styled toast before the HTTP response would claim a result
+ // the request has not produced yet. Terminal feedback only.
+ const result = await controller.run(
+ jobKey,
+ () => api.triggerCronJob(job.id, getJobProfile(job)),
);
- loadJobs();
+
+ if (
+ triggerControllerRef.current !== controller ||
+ selectedProfileRef.current !== viewProfile ||
+ !result.started
+ ) return;
+
+ showToast(`${label} ✓`, "success");
+ loadJobs(viewProfile);
} catch (e) {
- showToast(`${t.status.error}: ${e}`, "error");
+ if (
+ triggerControllerRef.current === controller &&
+ selectedProfileRef.current === viewProfile
+ ) {
+ showToast(`${t.status.error}: ${e}`, "error");
+ }
}
};
@@ -732,13 +812,13 @@ export default function CronPage() {
`${t.common.delete}: "${job ? truncateText(getJobTitle(job), 30) : id}"`,
"success",
);
- loadJobs();
+ loadJobs(selectedProfile);
} catch (e) {
showToast(`${t.status.error}: ${e}`, "error");
throw e;
}
},
- [jobs, loadJobs, showToast, t.common.delete, t.status.error],
+ [jobs, loadJobs, selectedProfile, showToast, t.common.delete, t.status.error],
),
});
@@ -790,7 +870,7 @@ export default function CronPage() {
{view === "blueprints" && (
<AutomationBlueprints
profile={selectedProfile === "all" ? "default" : selectedProfile}
- onCreated={loadJobs}
+ onCreated={() => loadJobs(selectedProfile)}
/>
)}
@@ -1094,11 +1174,12 @@ export default function CronPage() {
<Button
ghost
size="icon"
+ disabled={triggeringJobKeys.has(jobKey)}
title={t.cron.triggerNow}
aria-label={t.cron.triggerNow}
onClick={() => handleTrigger(job)}
>
- <Zap />
+ {triggeringJobKeys.has(jobKey) ? <Spinner /> : <Zap />}
</Button>
<Button