Skip to content

The agent that grows with you

fix(cron): Desktop shows Stop for a live run behind a refused Run-now

Teknium4e3a6a226512
diff --git a/apps/desktop/src/app/cron/run-control.test.ts b/apps/desktop/src/app/cron/run-control.test.ts
index e445a379f65..c3301ff8eca 100644
--- a/apps/desktop/src/app/cron/run-control.test.ts
+++ b/apps/desktop/src/app/cron/run-control.test.ts
@@ -1,7 +1,14 @@
import { describe, expect, it } from 'vitest'
import { cronEditorUpdates } from './cron-job-model'
-import { catchUpChoice, catchUpValue, jobLastCancelReason, jobRunInFlight, jobRunLive } from './run-control'
+import {
+ catchUpChoice,
+ catchUpValue,
+ jobLastCancelReason,
+ jobRunInFlight,
+ jobRunLive,
+ stopOutcome
+} from './run-control'
const SAVE = { deliver: 'local', model: '', name: 'Nightly', prompt: 'p', provider: '', schedule: '0 3 * * *' }
@@ -13,9 +20,31 @@ describe('cron Stop visibility', () => {
expect(jobRunInFlight(at('running'))).toBe(true)
expect(['completed', 'failed', 'cancelled', 'missed'].some(s => jobRunInFlight(at(s)))).toBe(false)
expect(jobRunInFlight({ latest_execution: null })).toBe(false)
- expect(jobLastCancelReason({ latest_execution: { error: 'job removed while running', id: 'e1', status: 'cancelled' } })).toBe(
- 'job removed while running'
+ expect(
+ jobLastCancelReason({ latest_execution: { error: 'job removed while running', id: 'e1', status: 'cancelled' } })
+ ).toBe('job removed while running')
+ })
+})
+
+describe('cron Stop behind a refused Run-now', () => {
+ it('keeps Stop for a live run whose newest row is a refused trigger, and settles it as stopped', () => {
+ const refused = {
+ claimed_at: '2026-10-25T21:00:05Z',
+ error: 'Fire claim was not acquired',
+ id: 'e2',
+ status: 'failed'
+ }
+
+ const live = { claimed_at: '2026-10-25T21:00:00Z', id: 'e1', status: 'running' }
+
+ expect(jobRunInFlight({ latest_execution: refused, live_execution: live })).toBe(true)
+ expect(stopOutcome({ latest_execution: refused, live_execution: live }, 'e1')).toBe('pending')
+ // The stopped run ended and is hidden behind the refused row: the accepted cancel is what stopped it.
+ expect(stopOutcome({ latest_execution: refused, live_execution: null }, 'e1')).toBe('cancelled')
+ expect(stopOutcome({ latest_execution: { ...live, status: 'completed' }, live_execution: null }, 'e1')).toBe(
+ 'finished'
)
+ expect(stopOutcome(undefined, 'e1')).toBe('cancelled')
})
})
@@ -39,6 +68,8 @@ describe('cron editor missed-run policy', () => {
expect(cronEditorUpdates({ ...SAVE }, { scriptOnlyJob: false })).not.toHaveProperty('catch_up')
expect(cronEditorUpdates({ ...SAVE, catchUp: catchUpValue('run') }, { scriptOnlyJob: false }).catch_up).toBe(true)
expect(stored).toBe('skip')
- expect(cronEditorUpdates({ ...SAVE, catchUp: catchUpValue('default') }, { scriptOnlyJob: true }).catch_up).toBeNull()
+ expect(
+ cronEditorUpdates({ ...SAVE, catchUp: catchUpValue('default') }, { scriptOnlyJob: true }).catch_up
+ ).toBeNull()
})
})
diff --git a/apps/desktop/src/app/cron/run-control.ts b/apps/desktop/src/app/cron/run-control.ts
index c2311934c64..93e65b42f87 100644
--- a/apps/desktop/src/app/cron/run-control.ts
+++ b/apps/desktop/src/app/cron/run-control.ts
@@ -5,8 +5,37 @@ import type { CronJob } from '@/types/hermes'
// so a claimed/running row is the run the Stop button can reach.
const IN_FLIGHT_STATUSES = new Set(['claimed', 'running'])
-export function jobRunInFlight(job: Pick<CronJob, 'latest_execution'>): boolean {
- return IN_FLIGHT_STATUSES.has(job.latest_execution?.status ?? '')
+type RunFields = Pick<CronJob, 'latest_execution' | 'live_execution'>
+
+// `live_execution` covers a scheduler-fired run hidden behind a newer refused Run-now row.
+export function jobRunInFlight(job: RunFields): boolean {
+ return IN_FLIGHT_STATUSES.has(job.latest_execution?.status ?? '') || Boolean(job.live_execution)
+}
+
+export type StopOutcome = 'cancelled' | 'finished' | 'pending'
+
+/**
+ * How a Stop aimed at `executionId` ('' until the cancel endpoint names it) ended, from a job-list
+ * snapshot taken in the stop's own backend scope. A removed job's run is stopped by the removal.
+ * When a newer row (a refused Run-now) hides the targeted attempt, the accepted cancel is the best
+ * evidence left, so it reads as cancelled.
+ */
+export function stopOutcome(job: RunFields | undefined, executionId: string): StopOutcome {
+ if (!job) {
+ return 'cancelled'
+ }
+
+ if (jobRunInFlight(job)) {
+ return 'pending'
+ }
+
+ const latest = job.latest_execution
+
+ if (executionId && latest && latest.id !== executionId) {
+ return 'cancelled'
+ }
+
+ return latest?.status === 'cancelled' ? 'cancelled' : 'finished'
}
// A run created this long before a Run-now click (renderer/backend clock skew) still counts as its run.
@@ -18,7 +47,7 @@ const TRIGGER_CLOCK_SLACK_MS = 2000
* since the click that already finished, so the button does not flicker back to Stop between
* the run ending and the trigger request returning.
*/
-export function jobRunLive(job: Pick<CronJob, 'latest_execution'>, triggerStartedAt?: number): boolean {
+export function jobRunLive(job: RunFields, triggerStartedAt?: number): boolean {
if (jobRunInFlight(job)) {
return true
}
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 8da7b630ada..8e71d417b62 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -1058,6 +1058,8 @@ export interface CronJob {
last_run_at?: null | string
/** The job's newest ledger attempt (``cron.jobs.list_jobs``); claimed/running = a run in flight. */
latest_execution?: CronJobExecution | null
+ /** The newest claimed/running attempt under a live owner, even when a newer refused row is latest. */
+ live_execution?: CronJobExecution | null
model?: null | string
name?: null | string
next_run_at?: null | string
diff --git a/cron/executions.py b/cron/executions.py
index 231b0a1d4ec..26f89649b71 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -708,13 +708,28 @@ def cancellable_execution(job_id: str) -> Optional[dict[str, Any]]:
acquired"), so ``live_inflight_execution`` (latest row only) would call the live run idle and a
cancel would never reach it.
"""
+ return live_executions([job_id]).get(str(job_id))
+
+
+def live_executions(job_ids: list[str]) -> dict[str, dict[str, Any]]:
+ """Each job's newest claimed/running attempt under a live owner, in one query (see
+ ``cancellable_execution``). The job list carries it as ``live_execution`` so a Stop button
+ still finds a run that a refused Run-now's newer row hides from ``latest_execution``."""
+ clean = [str(job_id) for job_id in dict.fromkeys(job_ids) if job_id]
+ if not clean:
+ return {}
+ placeholders = ",".join("?" for _ in clean)
with _transaction() as conn:
rows = conn.execute(
- """SELECT * FROM executions WHERE job_id=? AND status IN ('claimed', 'running')
+ f"""SELECT * FROM executions WHERE job_id IN ({placeholders}) AND status IN ('claimed', 'running')
ORDER BY julianday(claimed_at) DESC, claimed_at DESC, id DESC""",
- (job_id,),
+ clean,
).fetchall()
- return next((dict(row) for row in rows if _row_owner_live(row)), None)
+ live: dict[str, dict[str, Any]] = {}
+ for row in rows:
+ if row["job_id"] not in live and _row_owner_live(row):
+ live[row["job_id"]] = dict(row)
+ return live
def latest_executions(job_ids: list[str]) -> dict[str, dict[str, Any]]:
diff --git a/cron/jobs.py b/cron/jobs.py
index 5d5e5d30f0d..1809214b9df 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1990,13 +1990,15 @@ def list_jobs(include_disabled: bool = False) -> list[dict[str, Any]]:
if not include_disabled:
jobs = [j for j in jobs if j.get("enabled", True)]
try:
- from cron.executions import latest_executions
+ from cron.executions import latest_executions, live_executions
- latest = latest_executions([job.get("id", "") for job in jobs])
+ ids = [job.get("id", "") for job in jobs]
+ latest, live = latest_executions(ids), live_executions(ids)
except Exception:
- latest = {}
+ latest, live = {}, {}
for job in jobs:
job["latest_execution"] = latest.get(job.get("id", ""))
+ job["live_execution"] = live.get(job.get("id", ""))
return jobs
diff --git a/tests/cron/test_cron_cancel_bookkeeping.py b/tests/cron/test_cron_cancel_bookkeeping.py
index 8d4943bd997..385fb84648b 100644
--- a/tests/cron/test_cron_cancel_bookkeeping.py
+++ b/tests/cron/test_cron_cancel_bookkeeping.py
@@ -186,3 +186,21 @@ def test_a_capped_count_says_so_after_a_catch_up(store):
missed = [r for r in executions.list_executions(job_id=job["id"]) if r["status"] == "missed"]
assert len(missed) == 1
assert "counting stopped at 1000" in missed[0]["error"]
+
+
+def test_the_job_list_still_shows_a_live_run_behind_a_refused_trigger(store):
+ """Desktop's Stop reads the job list: a refused Run-now's newer row must not hide the live run."""
+ job = jobs.create_job(prompt="long", schedule="every 1h", deliver="local")
+ live = executions.create_execution(job["id"], source="test")["id"]
+ executions.mark_execution_running(live)
+ refused = executions.create_execution(job["id"], source="test")["id"]
+ executions.finish_execution(refused, success=False, error="Fire claim was not acquired")
+ with executions._transaction() as conn: # the refused row is the job's newest attempt
+ conn.execute("UPDATE executions SET claimed_at='2999-01-01T00:00:00+00:00' WHERE id=?", (refused,))
+
+ [listed] = jobs.list_jobs(include_disabled=True)
+ assert listed["latest_execution"]["id"] == refused
+ assert listed["live_execution"]["id"] == live
+
+ executions.finish_execution(live, success=True)
+ assert jobs.list_jobs(include_disabled=True)[0]["live_execution"] is None