The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): gate cron-run writes on scheduler ownership, re-evaluated per send
Austin Pickett46370fd2a206
diff --git a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.test.tsx b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.test.tsxindex 5c35991139e..ccc5fa1da50 100644--- a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.test.tsx@@ -2,14 +2,15 @@ import { cleanup, render, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { fmtDayTime } from '@/lib/time'-import { $readOnlyCronRuns, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'+import { $cronRunReadOnlyVerdicts, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'import type { CronJob, SessionInfo } from '@/types/hermes'import { SidebarCronJobsSection } from './cron-jobs-section'// The peek's run list comes off the backend; the liveness flags below are the-// endpoint's own (`hermes_cli/web_routers/cron.py` computes `is_active` as-// `ended_at IS NULL` + a recent-activity window).+// endpoint's own (`hermes_cli/web_routers/cron.py`: `is_active` is+// `ended_at IS NULL` + a 300s activity window, `scheduler_owned` is a live+// in-flight execution).const getCronJobRuns = vi.fn<() => Promise<SessionInfo[]>>()vi.mock('@/hermes', async importOriginal => {@@ -40,7 +41,7 @@ const run = (over: Partial<SessionInfo>): SessionInfo =>const runLabel = (row: SessionInfo) => fmtDayTime.format(new Date((row.last_active || row.started_at) * 1000))beforeEach(() => {- $readOnlyCronRuns.set(new Set())+ $cronRunReadOnlyVerdicts.set(new Map())getCronJobRuns.mockReset()})@@ -121,7 +122,20 @@ describe('SidebarCronJobsSection run peek — zombie cron runs (#88443)', () =>expect(isStoredTranscriptReadOnly('cron_live')).toBe(false)})- it('does not latch anything merely by rendering the peek', async () => {+ it('leaves a scheduler-owned run writable even past the 300s activity window', async () => {+ // A long tool call writes no heartbeat, so `is_active` goes false while the+ // scheduler still runs it — that is not a zombie.+ const busy = run({ ended_at: null, id: 'cron_busy', is_active: false, scheduler_owned: true })+ const { onOpenRun } = await renderRunsPeek([busy])++ const row = await screen.findByRole('button', { name: runLabel(busy) })+ row.click()++ expect(onOpenRun).toHaveBeenCalledWith('cron_busy', busy)+ expect(isStoredTranscriptReadOnly('cron_busy')).toBe(false)+ })++ it('does not gate anything merely by rendering the peek', async () => {await renderRunsPeek([run({ ended_at: null, id: 'cron_zombie', is_active: false })])await screen.findByRole('button', { name: runLabel(run({ ended_at: null, id: 'cron_zombie' })) })diff --git a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsxindex c90ac1f0dee..816629d742c 100644--- a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx+++ b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx@@ -21,7 +21,7 @@ import { $selectedStoredSessionId } from '@/store/session'import type { CronJob } from '@/types/hermes'import { jobState, jobTitle, nextRunOverdueMs, STATE_DOT } from '../../cron/job-state'-import { openCronRun } from '../../cron/open-cron-run'+import { openCronRun, reconcileCronRunVerdicts } from '../../cron/open-cron-run'import { SidebarPanelLabel } from '../../shell/sidebar-label'import { SidebarRowBody, SidebarRowLabel, SidebarRowLead, SidebarRowShell } from './chrome'@@ -420,6 +420,9 @@ function CronJobSidebarRuns({const load = () =>getCronJobRuns(jobId, PEEK_RUN_LIMIT).then(result => {+ // A fresh poll re-evaluates every run already opened (#88443).+ reconcileCronRunVerdicts(result)+if (!cancelled) {setRuns(result)}diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.tsindex 61a533af03c..81448b3e880 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts@@ -7,7 +7,7 @@ import type * as HermesModule from '@/hermes'import { textPart } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'import { $notifications } from '@/store/notifications'-import { $readOnlyCronRuns, markCronRunReadOnly } from '@/store/read-only-transcript'+import { $cronRunReadOnlyVerdicts, recordCronRunVerdict } from '@/store/read-only-transcript'import { setSessionOwnerHint, setSessions } from '@/store/session'import { $sessionTiles, sessionTileDelegate } from '@/store/session-states'import type { SessionInfo } from '@/types/hermes'@@ -16,7 +16,8 @@ import { useSessionTileDelegate } from './use-session-tile-delegate'vi.mock('@/hermes', async importActual => ({...(await importActual<typeof HermesModule>()),- getLatestSessionMessages: vi.fn(async () => ({ messages: [], session_id: '' }))+ getLatestSessionMessages: vi.fn(async () => ({ messages: [], session_id: '' })),+ getSession: vi.fn()}))vi.mock('@/store/gateway', async importActual => ({...(await importActual<Record<string, unknown>>()),@@ -24,7 +25,7 @@ vi.mock('@/store/gateway', async importActual => ({requestGatewayForProfile: vi.fn()}))-const { getLatestSessionMessages, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } = await import('@/hermes')+const { getLatestSessionMessages, getSession, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } = await import('@/hermes')const { requestGatewayForAgent, requestGatewayForProfile } = await import('@/store/gateway')const row = (over: Partial<SessionInfo>): SessionInfo =>@@ -899,30 +900,26 @@ describe('useSessionTileDelegate submitToSession', () => {describe('useSessionTileDelegate read-only cron run (#88443)', () => {- const storedId = 'cron_job-1_1700000000'- const runtimeId = 'rt-cron-zombie'+ const storedId = 'cron_job-1_20260929_120000'+ const runtimeId = 'rt-cron-run'beforeEach(() => {setSessions([])$notifications.set([])- $readOnlyCronRuns.set(new Set())+ $cronRunReadOnlyVerdicts.set(new Map())+ vi.mocked(requestGatewayForProfile).mockClear()vi.mocked(getLatestSessionMessages).mockReset()vi.mocked(getLatestSessionMessages).mockImplementation(async () => ({ messages: [], session_id: storedId }))+ vi.mocked(getSession).mockReset()})afterEach(() => {setSessions([])$notifications.set([])- $readOnlyCronRuns.set(new Set())+ $cronRunReadOnlyVerdicts.set(new Map())})- // The Cron surfaces latch a never-closed run read-only by STORED id; a tile- // resumed for that run must honour the same latch as the primary chat's- // `submit`, or moving the transcript into a tile reopens the write path.- it('refuses submitToSession into a cron run latched read-only', async () => {- setSessions([row({ id: storedId, profile: 'work-vps' })])- markCronRunReadOnly(storedId)-+ const submitIntoRun = async (text: string) => {const requestGateway = vi.fn(async () => ({}) as never)renderTile(requestGateway, {@@ -930,16 +927,46 @@ describe('useSessionTileDelegate read-only cron run (#88443)', () => {sessionStateByRuntimeIdRef: { current: new Map([[runtimeId, createClientSessionState(storedId, [])]]) }})- await sessionTileDelegate()!.submitToSession(runtimeId, 'into the dead cron session')+ await sessionTileDelegate()!.submitToSession(runtimeId, text)- expect(requestGateway).not.toHaveBeenCalledWith('prompt.submit', expect.anything(), expect.anything())- expect(requestGatewayForProfile).not.toHaveBeenCalledWith(- 'work-vps',- 'prompt.submit',- expect.anything(),- expect.anything(),- expect.anything()+ return requestGateway+ }++ const promptSubmitted = (text: string) =>+ vi+ .mocked(requestGatewayForProfile)+ .mock.calls.some(call => call[1] === 'prompt.submit' && (call[2] as { text?: string })?.text === text)++ // A tile holding a run the scheduler no longer owns (never closed) must+ // honour the same gate as the primary chat's `submit` — including a tile+ // restored after a restart, which no Cron surface ever evaluated.+ it('refuses a send into a never-closed run the scheduler does not own', async () => {+ setSessions([row({ id: storedId, profile: 'work-vps', source: 'cron' })])+ vi.mocked(getSession).mockResolvedValue(+ row({ ended_at: null, id: storedId, scheduler_owned: false, source: 'cron' }))++ const requestGateway = await submitIntoRun('into the dead cron session')++ expect(getSession).toHaveBeenCalledWith(storedId, expect.anything())+ expect(requestGateway).not.toHaveBeenCalledWith('prompt.submit', expect.anything(), expect.anything())+ expect(promptSubmitted('into the dead cron session')).toBe(false)expect($notifications.get().some(note => note.kind === 'info')).toBe(true)})++ // The review's blocker: a run marked read-only while it looked idle (a long+ // tool call) must not stay locked once the authoritative row says the+ // scheduler still owns it.+ it('re-evaluates a stale read-only verdict and sends once the run is owned', async () => {+ setSessions([row({ id: storedId, profile: 'work-vps', source: 'cron' })])+ recordCronRunVerdict(storedId, true)+ vi.mocked(getSession).mockResolvedValue(+ row({ ended_at: null, id: storedId, scheduler_owned: true, source: 'cron' })+ )++ await submitIntoRun('still running, send it')++ expect(promptSubmitted('still running, send it')).toBe(true)+ expect($notifications.get().some(note => note.kind === 'info')).toBe(false)+ })})diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex 6237891db48..063f065ec42 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@ -8,6 +8,7 @@ import {import {fetchStoredTranscriptAcrossBackends,getLatestSessionMessages,+ getSession,PROMPT_SUBMIT_REQUEST_TIMEOUT_MS} from '@/hermes'import { translateNow } from '@/i18n/runtime'@@ -33,6 +34,7 @@ import {} from '@/store/session-states'import type { SessionResumeResult } from '@/types/hermes'+import { refreshCronRunWriteGate } from '../../cron/open-cron-run'import type { usePromptActions } from '../../session/hooks/use-prompt-actions'import { singleFlightSessionResume } from '../../session/hooks/use-prompt-actions/single-flight-resume'import { markSessionRecentlyInterrupted, withSessionNotFoundResume } from '../../session/hooks/use-prompt-actions/utils'@@ -483,11 +485,19 @@ export function useSessionTileDelegate({submitToSession: async (runtimeId, text) => {const storedSessionId = storedSessionIdForRuntime(runtimeId)+ // A cron run's write gate is re-evaluated against its authoritative+ // row before the send (#88443) — the same gate as the primary chat's+ // `submit`, so a verdict never latches and a restored tile is gated.+ if (storedSessionId && !isReadOnlyRuntimeId(runtimeId)) {+ await refreshCronRunWriteGate(storedSessionId, id =>+ ownerForStoredSession(id).then(owner => getSession(id, profileScopeForSessionOwner(owner)))+ )+ }+// A read-only stored-transcript tile has no live runtime to submit- // into (#94724), and a never-closed cron run latched read-only by a- // Cron surface (#88443) stays closed to writes when it is later opened- // as a tile — same gate as the primary chat's `submit`. Refuse with the- // explanation instead of minting a misrouted prompt.+ // into (#94724), and a never-closed cron run the scheduler no longer+ // owns (#88443) stays closed to writes when it is opened as a tile.+ // Refuse with the explanation instead of minting a misrouted prompt.if (isReadOnlyRuntimeId(runtimeId) || isStoredTranscriptReadOnly(storedSessionId)) {notify({ kind: 'info', message: translateNow('desktop.readOnlyTranscriptSendBlocked') })diff --git a/apps/desktop/src/app/cron/index.tsx b/apps/desktop/src/app/cron/index.tsxindex 929a247ddfc..459168a6cf3 100644--- a/apps/desktop/src/app/cron/index.tsx+++ b/apps/desktop/src/app/cron/index.tsx@@ -87,7 +87,7 @@ import {validateCronEditor} from './cron-job-model'import { jobState, jobTitle, nextRunOverdueMs, STATE_DOT } from './job-state'-import { openCronRun } from './open-cron-run'+import { openCronRun, reconcileCronRunVerdicts } from './open-cron-run'const DEFAULT_DELIVER = 'local'@@ -916,6 +916,9 @@ function CronJobRuns({const load = () =>getCronJobRuns(jobId).then(result => {+ // A fresh poll re-evaluates every run already opened (#88443).+ reconcileCronRunVerdicts(result)+if (!cancelled) {setRuns(result)}diff --git a/apps/desktop/src/app/cron/open-cron-run.test.ts b/apps/desktop/src/app/cron/open-cron-run.test.tsindex d7743a7894e..5482f6ab90d 100644--- a/apps/desktop/src/app/cron/open-cron-run.test.ts+++ b/apps/desktop/src/app/cron/open-cron-run.test.ts@@ -1,71 +1,157 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-import { $readOnlyCronRuns, isCronRunReadOnly, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'--import { isResumableCronRun, openCronRun } from './open-cron-run'--const run = (over: Partial<{ ended_at: null | number; id: string; is_active: boolean }> = {}) => ({- ended_at: 1_700_000_600 as null | number,- id: 'cron_job-1_1700000000',+import { $cronRunReadOnlyVerdicts, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'++import { isResumableCronRun, openCronRun, reconcileCronRunVerdicts, refreshCronRunWriteGate } from './open-cron-run'++const NOW_MS = 1_800_000_000_000+const NOW_S = NOW_MS / 1000++// Backend row as the runs endpoint produces it: `is_active` is the 300s+// activity window, `scheduler_owned` the live-execution ownership (#88443).+const run = (+ over: Partial<{+ ended_at: null | number+ id: string+ is_active: boolean+ last_active: number+ scheduler_owned: boolean+ }> = {}+) => ({+ ended_at: null as null | number,+ id: 'cron_job-1_20260929_120000',is_active: false,+ last_active: NOW_S - 1800,...over})beforeEach(() => {- $readOnlyCronRuns.set(new Set())+ $cronRunReadOnlyVerdicts.set(new Map())})describe('isResumableCronRun', () => {- it('treats a live run as resumable (the scheduler agent still owns it)', () => {- expect(isResumableCronRun(run({ ended_at: null, is_active: true }))).toBe(true)+ it('keeps a scheduler-owned run live through a long tool call past the activity window', () => {+ // The review's blocker: 30 min without a tick → is_active=false, yet the+ // scheduler still runs it. Ownership, not freshness, decides.+ expect(isResumableCronRun(run({ is_active: false, scheduler_owned: true }), NOW_MS)).toBe(true)})- it('treats a properly closed run as resumable', () => {- expect(isResumableCronRun(run({ ended_at: 1_700_000_600, is_active: false }))).toBe(true)+ it('treats a never-closed run the scheduler does not own as a zombie, even if it ticked recently', () => {+ expect(isResumableCronRun(run({ is_active: true, last_active: NOW_S - 5, scheduler_owned: false }), NOW_MS)).toBe(+ false+ )})- it('treats a never-closed, not-live run as a zombie (NOT resumable)', () => {- // The incident shape: end_session never ran (watchdog kill / crash), so- // ended_at is NULL while no agent owns the session any more.- expect(isResumableCronRun(run({ ended_at: null, is_active: false }))).toBe(false)+ it('treats a properly closed run as resumable', () => {+ expect(isResumableCronRun(run({ ended_at: NOW_S - 60, scheduler_owned: false }), NOW_MS)).toBe(true)})- it('fails SAFE when an older backend omits is_active', () => {- expect(isResumableCronRun({ ended_at: null, is_active: undefined as never })).toBe(false)- expect(isResumableCronRun({ ended_at: 1_700_000_600, is_active: undefined as never })).toBe(true)+ it('falls back to the activity window against a backend without scheduler_owned', () => {+ expect(isResumableCronRun(run({ is_active: true }), NOW_MS)).toBe(true)+ expect(isResumableCronRun(run({ is_active: false }), NOW_MS)).toBe(false)+ // Session-detail rows on an older backend carry neither flag: same formula over last_active.+ expect(isResumableCronRun({ ended_at: null, last_active: NOW_S - 10 }, NOW_MS)).toBe(true)+ expect(isResumableCronRun({ ended_at: null, last_active: NOW_S - 600 }, NOW_MS)).toBe(false)})})describe('openCronRun', () => {- it('opens a live / completed run without latching it read-only', () => {+ it('opens a live / closed run writable', () => {const open = vi.fn()-- const live = run({ ended_at: null, is_active: true, id: 'live-run' })- const closed = run({ ended_at: 1_700_000_600, id: 'closed-run' })+ const live = run({ id: 'cron_live_20260929_120000', scheduler_owned: true })+ const closed = run({ ended_at: NOW_S - 60, id: 'cron_closed_20260929_120000' })openCronRun(live, open)openCronRun(closed, open)expect(open.mock.calls).toEqual([- ['live-run', live],- ['closed-run', closed]+ [live.id, live],+ [closed.id, closed]])- expect(isStoredTranscriptReadOnly('live-run')).toBe(false)- expect(isStoredTranscriptReadOnly('closed-run')).toBe(false)+ expect(isStoredTranscriptReadOnly(live.id)).toBe(false)+ expect(isStoredTranscriptReadOnly(closed.id)).toBe(false)})- it('opens a zombie run but latches it read-only before the route flips', () => {+ it('records a zombie read-only before the route flips', () => {+ const zombie = run({ scheduler_owned: false })+const open = vi.fn(() => {- // The route has flipped by the time the open runs: the latch must already- // be in place, or the first send lands inside the cron session.- expect(isStoredTranscriptReadOnly('zombie-run')).toBe(true)+ expect(isStoredTranscriptReadOnly(zombie.id)).toBe(true)})- const zombie = run({ ended_at: null, is_active: false, id: 'zombie-run' })-openCronRun(zombie, open)- expect(open).toHaveBeenCalledWith('zombie-run', zombie)- expect(isCronRunReadOnly('zombie-run')).toBe(true)+ expect(open).toHaveBeenCalledWith(zombie.id, zombie)+ })+})++describe('the verdict re-evaluates instead of latching', () => {+ it('a later poll showing the run live or closed makes it writable again, and back', () => {+ const id = 'cron_job-1_20260929_120000'++ openCronRun(run({ id, is_active: false }), vi.fn()) // older backend, stale tick+ expect(isStoredTranscriptReadOnly(id)).toBe(true)++ reconcileCronRunVerdicts([run({ id, is_active: true })]) // it ticked+ expect(isStoredTranscriptReadOnly(id)).toBe(false)++ reconcileCronRunVerdicts([run({ id, scheduler_owned: false })]) // its process died+ expect(isStoredTranscriptReadOnly(id)).toBe(true)++ reconcileCronRunVerdicts([run({ ended_at: NOW_S, id })]) // it closed+ expect(isStoredTranscriptReadOnly(id)).toBe(false)+ })++ it('a poll never gates runs the user did not open', () => {+ reconcileCronRunVerdicts([run({ id: 'cron_other_20260929_120000', scheduler_owned: false })])++ expect(isStoredTranscriptReadOnly('cron_other_20260929_120000')).toBe(false)+ })++ it('the pre-send refresh reads the authoritative row and clears a stale zombie verdict', async () => {+ const id = 'cron_job-1_20260929_120000'+ openCronRun(run({ id, scheduler_owned: false }), vi.fn())++ const fetchRow = vi.fn(async () => ({ ended_at: NOW_S, last_active: NOW_S, source: 'cron' }))++ expect(await refreshCronRunWriteGate(id, fetchRow)).toBe(false)+ expect(fetchRow).toHaveBeenCalledWith(id)+ expect(isStoredTranscriptReadOnly(id)).toBe(false)+ })+})++describe('refreshCronRunWriteGate — restored tab after a restart (no verdict yet)', () => {+ const id = 'cron_job-1_20260929_120000'++ it('gates a restored zombie run by its cron run id', async () => {+ const fetchRow = vi.fn(async () => ({ ended_at: null, last_active: 0, scheduler_owned: false, source: 'cron' }))++ expect(await refreshCronRunWriteGate(id, fetchRow)).toBe(true)+ expect(isStoredTranscriptReadOnly(id)).toBe(true)+ })++ it('leaves a restored live run writable', async () => {+ const fetchRow = vi.fn(async () => ({ ended_at: null, last_active: 0, scheduler_owned: true, source: 'cron' }))++ expect(await refreshCronRunWriteGate(id, fetchRow)).toBe(false)+ })++ it('fails closed when an unknown cron run cannot be read, but keeps a known verdict', async () => {+ const failing = vi.fn(async () => {+ throw new Error('offline')+ })++ expect(await refreshCronRunWriteGate(id, failing)).toBe(true)++ openCronRun(run({ id, scheduler_owned: true }), vi.fn())+ expect(await refreshCronRunWriteGate(id, failing)).toBe(false)+ })++ it('never fetches for an ordinary session', async () => {+ const fetchRow = vi.fn()++ expect(await refreshCronRunWriteGate('20260929_120000_abc123', fetchRow)).toBe(false)+ expect(await refreshCronRunWriteGate(null, fetchRow)).toBe(false)+ expect(fetchRow).not.toHaveBeenCalled()})})diff --git a/apps/desktop/src/app/cron/open-cron-run.ts b/apps/desktop/src/app/cron/open-cron-run.tsindex c2ea8aceefa..9ba2acfdf22 100644--- a/apps/desktop/src/app/cron/open-cron-run.ts+++ b/apps/desktop/src/app/cron/open-cron-run.ts@@ -1,47 +1,125 @@-import { markCronRunReadOnly } from '@/store/read-only-transcript'+import { hasCronRunVerdict, isCronRunReadOnly, recordCronRunVerdict } from '@/store/read-only-transcript'import type { SessionInfo } from '@/types/hermes'+type CronRunLiveness = Pick<SessionInfo, 'ended_at' | 'last_active' | 'scheduler_owned'> &+ Partial<Pick<SessionInfo, 'is_active'>>++type CronRunRow = CronRunLiveness & Pick<SessionInfo, 'id'>++// Mirrors the backend's activity window (`hermes_cli/web_routers/cron.py`,+// `sessions.py::_ACTIVE_WINDOW_S`). Used ONLY against an older backend that+// predates `scheduler_owned`.+const ACTIVITY_WINDOW_MS = 300_000++// `cron/scheduler.py::run_job` names every agent run `cron_{job_id}_{YYYYmmdd_HHMMSS}`.+const CRON_RUN_SESSION_ID = /^cron_.+_\d{8}_\d{6}$/+/*** Cron run sessions are autonomous scheduled executions, never interactive- * chat targets (#88443). Two states may be opened as a normal, WRITABLE- * desktop chat: the run is still LIVE (`is_active`, the scheduler's agent is- * executing it), or the run was properly CLOSED (`ended_at` stamped by- * `_finalize_cron_session`).+ * chat targets (#88443). Two states may be written to as a normal desktop+ * chat: the run is still LIVE, or it was properly CLOSED (`ended_at` stamped+ * by `_finalize_cron_session`).*- * A run with `ended_at` NULL that is not live never got its `end_session` —- * the watchdog killed the process, the run crashed, or the connection- * dropped. It is a ZOMBIE: the row still looks open while nothing owns it, and- * resuming it as a desktop chat routes the user's messages into a dead- * `source='cron'` session, where the cron agent executes unrelated desktop- * work. Such a run opens READ-ONLY instead.+ * LIVE means the scheduler OWNS the run (`scheduler_owned`: its in-flight+ * execution is held by a live process). It is NOT `is_active`, which is a+ * 300s activity window: a live run inside a long `terminal` / `execute_code`+ * / `delegate_task` call writes no heartbeat and reads inactive exactly like a+ * zombie. A run with `ended_at` NULL that the scheduler does not own never got+ * its `end_session` — a ZOMBIE — and is view-only.*- * `is_active` is computed by the runs endpoint (`hermes_cli/web_routers/- * cron.py`) as `ended_at IS NULL` plus a recent-activity window, so an older- * backend that omits the flag fails SAFE here: the run reads as a zombie and- * opens read-only rather than writable.+ * An older backend without `scheduler_owned` falls back to the activity window+ * (the backend's `is_active`, or the same formula over `last_active` for rows+ * that carry no flag). That is the best such a backend can say, and the verdict+ * is re-evaluated on every refresh and send, so it never latches.*/-export function isResumableCronRun(run: Pick<SessionInfo, 'ended_at' | 'is_active'>): boolean {- return run.is_active === true || run.ended_at != null+export function isResumableCronRun(run: CronRunLiveness, nowMs = Date.now()): boolean {+ if (run.ended_at != null) {+ return true+ }++ if (typeof run.scheduler_owned === 'boolean') {+ return run.scheduler_owned+ }++ if (typeof run.is_active === 'boolean') {+ return run.is_active+ }++ return typeof run.last_active === 'number' && nowMs - run.last_active * 1000 < ACTIVITY_WINDOW_MS+}++export function isCronRunSessionId(storedSessionId: null | string | undefined): boolean {+ return Boolean(storedSessionId && CRON_RUN_SESSION_ID.test(storedSessionId.trim()))+}++function recordRunVerdict(run: CronRunRow): void {+ recordCronRunVerdict(run.id, !isResumableCronRun(run))}/*** The single door every Cron surface (the sidebar run peek and the Cron page* history) uses to open a run's session, so the policy above is applied in one- * place and cannot drift between callers.- *- * A never-closed run is latched read-only before the route flips: the- * transcript still paints, but `submit` refuses to route a send into the dead- * session (see `store/read-only-transcript`).+ * place and cannot drift between callers. The verdict is recorded before the+ * route flips, so the first send already sees it.*/-export function openCronRun<Run extends Pick<SessionInfo, 'ended_at' | 'id' | 'is_active'>>(- run: Run,- open: (sessionId: string, session: Run) => void-): void {- if (!isResumableCronRun(run)) {- markCronRunReadOnly(run.id)- }+export function openCronRun<Run extends CronRunRow>(run: Run, open: (sessionId: string, session: Run) => void): void {+ recordRunVerdict(run)// The ROW rides along so the open can pin its owning (connection, profile)// (#82527).open(run.id, run)}++/**+ * Fold a fresh page of run rows (a Cron surface poll) into the verdicts of runs+ * the desktop already evaluated, so a zombie-looking run that later ticks or+ * closes becomes writable again — and a live one that dies becomes view-only —+ * without waiting for a send. Rows never opened are left alone.+ */+export function reconcileCronRunVerdicts(runs: readonly CronRunRow[]): void {+ for (const run of runs) {+ if (hasCronRunVerdict(run.id)) {+ recordRunVerdict(run)+ }+ }+}++/**+ * Re-evaluate a cron run's write gate against its AUTHORITATIVE row right+ * before a send, then report whether the send must be refused.+ *+ * Covers what the Cron surfaces cannot: a verdict that went stale while no+ * surface was polling, and a restored route/tab after an app restart, where no+ * surface ever evaluated the run (the in-memory verdicts start empty). Such a+ * session is recognised by its cron run id. Any other session returns+ * immediately without a request.+ *+ * An unreadable row keeps a known verdict; an unknown run fails CLOSED — a+ * send into a possibly-dead cron session is exactly the misroute to prevent.+ */+export async function refreshCronRunWriteGate(+ storedSessionId: null | string | undefined,+ fetchRow: (storedSessionId: string) => Promise<CronRunLiveness & Partial<Pick<SessionInfo, 'source'>>>+): Promise<boolean> {+ const id = storedSessionId?.trim()++ if (!id || !(isCronRunSessionId(id) || hasCronRunVerdict(id))) {+ return false+ }++ try {+ const row = await fetchRow(id)++ if (row.source && row.source !== 'cron') {+ recordCronRunVerdict(id, false)+ } else {+ recordRunVerdict({ ...row, id })+ }+ } catch {+ if (!hasCronRunVerdict(id)) {+ recordCronRunVerdict(id, true)+ }+ }++ return isCronRunReadOnly(id)+}diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex 793a652108e..f8071a7489d 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@ -15,6 +15,7 @@ import { requestGatewayForAgent } from '@/store/gateway'import { $goalsBySession, setSessionGoal } from '@/store/goals'import { $hudMode } from '@/store/hud'import { $notifications, clearNotifications } from '@/store/notifications'+import { $cronRunReadOnlyVerdicts } from '@/store/read-only-transcript'import {$busy,$connection,@@ -6578,3 +6579,63 @@ describe('usePromptActions derives plans from the runtime slice ($sessionStates))})})++describe('usePromptActions cron run write gate (#88443)', () => {+ const storedId = 'cron_job-1_20260929_120000'++ afterEach(() => {+ cleanup()+ $notifications.set([])+ $cronRunReadOnlyVerdicts.set(new Map())+ setSessions(() => [])+ vi.mocked(getSession).mockReset()+ })++ const renderRestoredRun = async (requestGateway: ReturnType<typeof vi.fn>) => {+ let handle: HarnessHandle | null = null++ // A route/tab restored after an app restart: no Cron surface evaluated the+ // run, so there is no verdict yet — the send itself must gate it.+ await actRender(+ <Harness+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway as never}+ storedSessionId={storedId}+ />+ )++ return handle!+ }++ it('refuses a send into a restored never-closed run the scheduler does not own', async () => {+ vi.mocked(getSession).mockResolvedValue(+ sessionInfo({ ended_at: null, id: storedId, scheduler_owned: false, source: 'cron' })+ )++ const requestGateway = vi.fn(async () => ({}) as never)+ const handle = await renderRestoredRun(requestGateway)++ expect(await handle.submitText('into the dead cron session')).toBe(false)+ expect(getSession).toHaveBeenCalledWith(storedId, expect.anything())+ expect(requestGateway).not.toHaveBeenCalledWith('prompt.submit', expect.anything(), expect.anything())+ expect($notifications.get().some(note => note.kind === 'info')).toBe(true)+ })++ it('sends into a run past the activity window while the scheduler still owns it', async () => {+ $cronRunReadOnlyVerdicts.set(new Map([[storedId, true]])) // looked idle earlier+ vi.mocked(getSession).mockResolvedValue(+ sessionInfo({ ended_at: null, id: storedId, is_active: false, scheduler_owned: true, source: 'cron' })+ )++ const requestGateway = vi.fn(async () => ({}) as never)+ const handle = await renderRestoredRun(requestGateway)++ expect(await handle.submitText('still running')).toBe(true)+ expect(requestGateway).toHaveBeenCalledWith(+ 'prompt.submit',+ expect.objectContaining({ text: 'still running' }),+ 1_800_000+ )+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 25c838eed00..f0bf0e40f42 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -1,13 +1,13 @@import type { PromptSubmitResult } from '@hermes/shared'import { type MutableRefObject, useCallback } from 'react'-import { PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'+import { getSession, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'import { translateNow, type Translations } from '@/i18n'import { type ChatMessage, finalizeInterruptedMessages, textPart } from '@/lib/chat-messages'import { optimisticAttachmentRef } from '@/lib/chat-runtime'import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'import { setMutableRef } from '@/lib/mutable-ref'-import { transcriptRefreshIfBehind } from '@/lib/stale-transcript-guard'+import { profileScopeForSessionOwner, transcriptRefreshIfBehind } from '@/lib/stale-transcript-guard'import {isVoicePlaybackActive,markVoicePlaybackInterrupted,@@ -25,7 +25,7 @@ import { noteMessageSent } from '@/store/desktop-metrics'import { $hudMode } from '@/store/hud'import { clearNotifications, notify, notifyError } from '@/store/notifications'import { consumePendingCredentialWarning, requestDesktopOnboarding } from '@/store/onboarding'-import { isStoredTranscriptReadOnly } from '@/store/read-only-transcript'+import { isCronRunReadOnly, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'import {$activeSessionId,$sessions,@@ -43,10 +43,11 @@ import {profileScopeForTranscriptSession,resolveActiveTranscriptSession} from '../../../contrib/hooks/use-background-sync'+import { isCronRunSessionId, refreshCronRunWriteGate } from '../../../cron/open-cron-run'import type { ClientSessionState } from '../../../types'import { routeTargetFromToken, sessionContextDrift } from '../session-context-drift'import type { CreateBackendSessionForSend } from '../use-session-actions/create-overrides'-import { resolveSessionProfile } from '../use-session-actions/utils'+import { resolveSessionOwner, resolveSessionProfile } from '../use-session-actions/utils'import { registerRecoveredRuntime, singleFlightSessionResume, takeRecoveredRuntime } from './single-flight-resume'import {@@ -288,10 +289,29 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {// to another chat.let targetStoredSessionId = options?.storedSessionId ?? selectedStoredSessionIdRef.current+ // A cron run's write gate is re-evaluated against its authoritative row+ // right here (#88443): a verdict recorded when the run looked idle+ // must not outlive the run ticking or closing, and a tab restored+ // after a restart (no verdict yet) is gated too. No-op for non-cron+ // sessions. If the user moved to another chat meanwhile, drop the send+ // rather than route it on a stale target — the draft stays.+ if (isCronRunSessionId(targetStoredSessionId) || isCronRunReadOnly(targetStoredSessionId)) {+ const viewBeforeGate = selectedStoredSessionIdRef.current++ await refreshCronRunWriteGate(targetStoredSessionId, id =>+ resolveSessionOwner(id).then(owner => getSession(id, profileScopeForSessionOwner(owner)))+ )++ if (selectedStoredSessionIdRef.current !== viewBeforeGate) {+ return false+ }+ }+// A read-only stored-transcript open (#94724: owner unresolvable under- // registry topology) has no routable live runtime — refuse the send- // with the explanation rather than minting a prompt on a backend that- // never owned the session.+ // registry topology, or a never-closed cron run the scheduler no longer+ // owns) has no routable live runtime — refuse the send with the+ // explanation rather than minting a prompt on a backend that never owned+ // the session.if (isStoredTranscriptReadOnly(targetStoredSessionId)) {notify({ kind: 'info', message: copy.readOnlyTranscriptSendBlocked })diff --git a/apps/desktop/src/store/read-only-transcript.test.ts b/apps/desktop/src/store/read-only-transcript.test.tsindex ee0fc053237..d8f0a69bf6d 100644--- a/apps/desktop/src/store/read-only-transcript.test.ts+++ b/apps/desktop/src/store/read-only-transcript.test.ts@@ -3,15 +3,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { $connectionsRegistry } from './connections'import { $profiles } from './profile'import {- $readOnlyCronRuns,+ $cronRunReadOnlyVerdicts,$readOnlyStoredTranscripts,clearStoredTranscriptReadOnly,isCronRunReadOnly,isReadOnlyRuntimeId,isStoredTranscriptReadOnly,- markCronRunReadOnly,markStoredTranscriptReadOnly,readOnlyRuntimeIdFor,+ recordCronRunVerdict,resumeWithStoredTranscriptFallback} from './read-only-transcript'import { assertSessionOwnerResolved } from './session-owner-resolution'@@ -28,7 +28,7 @@ beforeEach(() => {$connectionsRegistry.set(null)$profiles.set([])$readOnlyStoredTranscripts.set(new Set())- $readOnlyCronRuns.set(new Set())+ $cronRunReadOnlyVerdicts.set(new Map())})afterEach(() => {@@ -145,36 +145,40 @@ describe('read-only stored-transcript resume (#94724 no-owner recovery)', () =>})describe('read-only cron runs (#88443 zombie cron session)', () => {- it('blocks writes on a cron run latched read-only', () => {- markCronRunReadOnly('cron_job-1_1700000000')+ it('blocks writes on a cron run whose verdict is read-only', () => {+ recordCronRunVerdict('cron_job-1_20260929_120000', true)- expect(isCronRunReadOnly('cron_job-1_1700000000')).toBe(true)+ expect(isCronRunReadOnly('cron_job-1_20260929_120000')).toBe(true)// The submit path's gate: one answer for every write surface.- expect(isStoredTranscriptReadOnly('cron_job-1_1700000000')).toBe(true)+ expect(isStoredTranscriptReadOnly('cron_job-1_20260929_120000')).toBe(true)// Unrelated ids stay writable.- expect(isStoredTranscriptReadOnly('cron_job-1_1800000000')).toBe(false)+ expect(isStoredTranscriptReadOnly('cron_job-1_20260929_130000')).toBe(false)expect(isStoredTranscriptReadOnly(null)).toBe(false)})- it('survives a live resume clearing the owner-recovery latch', () => {- markCronRunReadOnly('cron-keep')+ it('a fresh verdict reopens the run — nothing latches', () => {+ recordCronRunVerdict('cron-flip', true)+ recordCronRunVerdict('cron-flip', false)++ expect(isStoredTranscriptReadOnly('cron-flip')).toBe(false)+ })++ it('survives a live resume clearing the owner-recovery flag', () => {+ recordCronRunVerdict('cron-keep', true)markStoredTranscriptReadOnly('cron-keep')- // Exactly what a successful resume does to the #94724 latch — the cron- // latch must NOT be collateral damage, or the guard evaporates the moment- // the transcript paints.+ // Exactly what a successful resume does to the #94724 flag — the cron+ // verdict must NOT be collateral damage, or the guard evaporates the+ // moment the transcript paints.clearStoredTranscriptReadOnly('cron-keep')expect(isStoredTranscriptReadOnly('cron-keep')).toBe(true)- expect(isStoredTranscriptReadOnly('legacy-owner-recovery')).toBe(false)})- it('ignores blank ids and is idempotent', () => {- markCronRunReadOnly(' ')- expect(isCronRunReadOnly('')).toBe(false)+ it('ignores blank ids', () => {+ recordCronRunVerdict(' ', true)- markCronRunReadOnly('cron-twice')- markCronRunReadOnly('cron-twice')- expect([...$readOnlyCronRuns.get()]).toEqual(['cron-twice'])+ expect(isCronRunReadOnly('')).toBe(false)+ expect($cronRunReadOnlyVerdicts.get().size).toBe(0)})})diff --git a/apps/desktop/src/store/read-only-transcript.ts b/apps/desktop/src/store/read-only-transcript.tsindex 4bde30b5faa..8409335e5bb 100644--- a/apps/desktop/src/store/read-only-transcript.ts+++ b/apps/desktop/src/store/read-only-transcript.ts@@ -16,10 +16,10 @@* after the single-match owner backfill stamps the row) clears the flag.** A second, unrelated reason a stored transcript is read-only lives here too:- * a cron run the scheduler never closed (#88443). It uses its own latch so a- * live resume cannot clear it — see `markCronRunReadOnly` below, which- * `isStoredTranscriptReadOnly` also reports, so every write path gets one- * answer.+ * a cron run the scheduler no longer owns but never closed (#88443). It keeps+ * its own verdict (see `$cronRunReadOnlyVerdicts` below) so a live resume+ * cannot clear it, and `isStoredTranscriptReadOnly` reports both, so every+ * write path gets one answer.*/import { atom } from 'nanostores'@@ -61,41 +61,45 @@ export function isStoredTranscriptReadOnly(storedSessionId: null | string | undeconst id = storedSessionId.trim()- return $readOnlyStoredTranscripts.get().has(id) || $readOnlyCronRuns.get().has(id)+ return $readOnlyStoredTranscripts.get().has(id) || isCronRunReadOnly(id)}/**- * Cron runs opened from the desktop's Cron surfaces (#88443).+ * Cron run write gate (#88443), one VERDICT per run session the desktop has+ * evaluated — never a permanent latch.*- * A cron run is an autonomous scheduled execution, never an interactive chat- * target. A run whose `ended_at` is NULL while no agent owns it is a ZOMBIE:- * the scheduler's `end_session` never ran (watchdog kill, crash, connection- * drop), so the row still looks open. Resuming it as a normal desktop chat- * routes the user's messages into a dead `source='cron'` session, and the- * run's own agent then executes unrelated desktop work under the cron- * identity.+ * A cron run is an autonomous scheduled execution. A run whose `ended_at` is+ * NULL while the scheduler no longer owns it is a ZOMBIE (watchdog kill,+ * crash, connection drop): resuming it as a desktop chat routes the user's+ * messages into a dead `source='cron'` session. A zombie's verdict is `true`+ * (read-only); a live or closed run's is `false`.*- * This latch is deliberately SEPARATE from the owner-recovery set above: a- * successful live resume clears that one (the owner proved routable again),- * but a never-closed cron run must stay non-writable for as long as this app- * session remembers it. The transcript still opens — `submit` refuses the- * send with the read-only explanation, and starting a fresh chat is the way- * forward.+ * The verdict is RE-EVALUATED whenever fresher run data arrives — every Cron+ * surface poll and, authoritatively, right before any send+ * (`refreshCronRunWriteGate`) — so a run that looked idle during a long tool+ * call, then ticked or closed, becomes writable again. It is deliberately+ * separate from the owner-recovery set above: a successful live resume of a+ * zombie must not clear it.*/-export const $readOnlyCronRuns = atom<ReadonlySet<string>>(new Set())+export const $cronRunReadOnlyVerdicts = atom<ReadonlyMap<string, boolean>>(new Map())-export function markCronRunReadOnly(storedSessionId: string): void {+export function recordCronRunVerdict(storedSessionId: string, readOnly: boolean): void {const id = storedSessionId.trim()+ const current = $cronRunReadOnlyVerdicts.get()- if (!id || $readOnlyCronRuns.get().has(id)) {+ if (!id || current.get(id) === readOnly) {return}- $readOnlyCronRuns.set(new Set([...$readOnlyCronRuns.get(), id]))+ $cronRunReadOnlyVerdicts.set(new Map(current).set(id, readOnly))+}++export function hasCronRunVerdict(storedSessionId: null | string | undefined): boolean {+ return Boolean(storedSessionId && $cronRunReadOnlyVerdicts.get().has(storedSessionId.trim()))}export function isCronRunReadOnly(storedSessionId: null | string | undefined): boolean {- return Boolean(storedSessionId && $readOnlyCronRuns.get().has(storedSessionId.trim()))+ return Boolean(storedSessionId && $cronRunReadOnlyVerdicts.get().get(storedSessionId.trim()) === true)}/** Synthetic runtime-id namespace for read-only tiles: a stored transcriptdiff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex dc2eb8e7064..ba1b527c9ea 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -583,6 +583,12 @@ export interface SessionInfo {actual_cost_usd?: null | numberestimated_cost_usd?: null | numberis_active: boolean+ /** Cron run rows only (`source === 'cron'`): the scheduler still OWNS this+ * never-closed run — its in-flight execution is held by a live process.+ * Unlike {@link is_active} (a 300s activity window) it stays true through a+ * long tool call and is false for a zombie whose process died (#88443).+ * Undefined against older backends and for non-cron rows. */+ scheduler_owned?: booleanlast_active: numbermessage_count: numbermodel: null | stringdiff --git a/cron/executions.py b/cron/executions.pyindex 4f40500bfc3..b6afa0d3797 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -482,6 +482,21 @@ def latest_execution(job_id: str) -> Optional[Dict[str, Any]]:return rows[0] if rows else None+def live_inflight_execution(job_id: str) -> Optional[Dict[str, Any]]:+ """The job's latest attempt while it is still claimed/running under a LIVE owner, else ``None``.++ This is scheduler OWNERSHIP, not recent activity: a run inside a long tool call writes no+ heartbeat yet stays owned, while a run whose process died (watchdog kill, crash) does not.+ Read-only — unlike ``recover_interrupted_executions`` it never rewrites a row.+ """+ record = latest_execution(job_id)+ if not record or record.get("status") not in ("claimed", "running"):+ return None+ if not _owner_is_live(int(record["pid"]), record.get("process_started_at")):+ return None+ return record++def latest_executions(job_ids: List[str]) -> Dict[str, Dict[str, Any]]:"""Load latest execution for many jobs in one query."""clean = [str(job_id) for job_id in dict.fromkeys(job_ids) if job_id]diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.pyindex d2326ad332c..ebfaa5e5ff9 100644--- a/hermes_cli/web_routers/cron.py+++ b/hermes_cli/web_routers/cron.py@@ -444,6 +444,61 @@ def _list_cron_output_runs(}]+_CRON_RUN_SESSION_ID = re.compile(r"^cron_(.+)_\d{8}_\d{6}$")+# The run's session row is written just AFTER its execution claim; the grace only+# absorbs float/ISO rounding between the two clocks on one host.+_OWNERSHIP_CLAIM_GRACE_SECONDS = 5.0+++def _live_inflight_execution(canonical_job_id: str) -> Optional[Dict[str, Any]]:+ """The job's claimed/running ledger attempt under a live owner, or None (fail closed).++ Must run inside the owner-home scope so it reads the OWNER's executions.db.+ """+ try:+ from cron.executions import live_inflight_execution++ return live_inflight_execution(canonical_job_id)+ except Exception:+ return None+++def _run_owned_by(session: Dict[str, Any], inflight: Optional[Dict[str, Any]]) -> bool:+ """Whether the scheduler still OWNS this never-closed run session (#88443).++ ``is_active`` is a 300s activity window, so a live run inside a long tool call+ (no heartbeat, no message) reads inactive exactly like a zombie whose process+ died. Ownership is the durable answer: the job's in-flight attempt is held by a+ live process and this session started under that claim. An older never-closed+ run of the same job predates the claim, so it stays a zombie.+ """+ if not inflight or session.get("ended_at") is not None:+ return False+ claimed_at = _iso_to_epoch(inflight.get("claimed_at"))+ try:+ started_at = float(session.get("started_at") or 0)+ except (TypeError, ValueError):+ return False+ return claimed_at is not None and started_at >= claimed_at - _OWNERSHIP_CLAIM_GRACE_SECONDS+++def cron_run_scheduler_owned(session: Dict[str, Any], profile: Optional[str] = None) -> Optional[bool]:+ """``scheduler_owned`` for one session row, or None when it is not a cron run session.++ The session-detail endpoint stamps this so a client re-checking a run it+ already has open (a restored tab, a send) gets the same answer as the runs list.+ """+ if session.get("source") != "cron":+ return None+ match = _CRON_RUN_SESSION_ID.match(str(session.get("id") or ""))+ if not match:+ return None+ if session.get("ended_at") is not None:+ return False+ with _owner_home_scope(profile):+ return _run_owned_by(session, _live_inflight_execution(match.group(1)))++def _list_cron_job_runs_sync(job_id: str, profile: Optional[str] = None, limit: int = 20):"""Run history for a cron job, newest first: agent sessions PLUS script-only fires.@@ -485,8 +540,10 @@ def _list_cron_job_runs_sync(job_id: str, profile: Optional[str] = None, limit:db.close()now = time.time()+ inflight = _live_inflight_execution(canonical)for s in session_runs:s["is_active"] = s.get("ended_at") is None and (now - s.get("last_active", s.get("started_at", 0))) < 300+ s["scheduler_owned"] = _run_owned_by(s, inflight)s["archived"] = bool(s.get("archived"))if selected:s["profile"] = selecteddiff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex 3188bdc1a0a..32f14a08819 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -532,6 +532,13 @@ async def get_session_detail(session_id: str, profile: Optional[str] = None):# clients resolve them to whichever gateway happened to be active.session["profile"] = _serving_profile(profile)session["is_default_profile"] = session["profile"] == "default"+ # A cron run's liveness is scheduler ownership, not the 300s activity+ # window (#88443): a run inside a long tool call is still owned.+ from hermes_cli.web_routers.cron import cron_run_scheduler_owned++ owned = cron_run_scheduler_owned(session, profile)+ if owned is not None:+ session["scheduler_owned"] = ownedreturn sessionreturn await asyncio.to_thread(_with_db, profile, _detail, read_only=True)diff --git a/tests/hermes_cli/test_cron_run_scheduler_ownership.py b/tests/hermes_cli/test_cron_run_scheduler_ownership.pynew file mode 100644index 00000000000..563a55db3ee--- /dev/null+++ b/tests/hermes_cli/test_cron_run_scheduler_ownership.py@@ -0,0 +1,162 @@+"""A never-closed cron run is live while the scheduler OWNS it, not while it ticked recently (#88443).++``is_active`` on a run row is a 300s activity window. A live run inside a long tool call writes no+heartbeat, so it reads inactive exactly like a zombie whose process died. ``scheduler_owned`` is+the durable answer the desktop keys its view-only decision on; these tests drive the real+execution ledger in a temp HERMES_HOME.+"""++import sqlite3+import subprocess+import sys+from pathlib import Path++import pytest++import hermes_cli.web_routers.cron as _rt_cron+++def homes(tmp_path, monkeypatch):+ from hermes_cli import profiles++ default_home = tmp_path / ".hermes"+ profiles_root = default_home / "profiles"+ worker_home = profiles_root / "worker_alpha"+ for home in (default_home, worker_home):+ (home / "cron").mkdir(parents=True, exist_ok=True)+ (home / "config.yaml").write_text("model: test-model\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(default_home))+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)+ monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)+ return {"default": default_home, "worker_alpha": worker_home}+++def _claim(home: Path, job_id: str) -> dict:+ """Create + start a ledger attempt owned by THIS (live) process, inside ``home``."""+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ from cron.executions import create_execution, mark_execution_running++ token = set_hermes_home_override(str(home))+ try:+ record = create_execution(job_id, source="test")+ return mark_execution_running(record["id"]) or record+ finally:+ reset_hermes_home_override(token)+++def _claimed_epoch(execution: dict) -> float:+ epoch = _rt_cron._iso_to_epoch(execution["claimed_at"])+ assert epoch is not None+ return epoch+++def _dead_pid() -> int:+ proc = subprocess.Popen([sys.executable, "-c", "pass"])+ proc.wait()+ return proc.pid+++def _kill_owner(home: Path, execution_id: str) -> None:+ conn = sqlite3.connect(home / "cron" / "executions.db")+ try:+ conn.execute("UPDATE executions SET pid=? WHERE id=?", (_dead_pid(), execution_id))+ conn.commit()+ finally:+ conn.close()+++def _runs(monkeypatch, job_id: str, rows: list, profile: str = "default") -> dict:+ class _FakeDB:+ def list_cron_job_runs(self, canonical, limit=20, offset=0):+ return [dict(r) for r in rows]++ def close(self):+ pass++ monkeypatch.setattr(_rt_cron, "_open_session_db_for_profile", lambda _p, *, read_only: _FakeDB())+ monkeypatch.setattr(_rt_cron, "_job_owner_profile", lambda _j, _p: profile)+ monkeypatch.setattr(+ _rt_cron, "_call_cron_for_profile",+ lambda _p, cmd, *_a, **_k: {"id": job_id} if cmd == "get_job" else None,+ )+ result = _rt_cron._list_cron_job_runs_sync(job_id, limit=10)+ return {run["id"]: run for run in result["runs"]}+++def _open_row(job_id: str, suffix: str, started_at: float) -> dict:+ # last_active far in the past: the activity window alone would call it dead.+ return {+ "id": f"cron_{job_id}_{suffix}", "source": "cron", "started_at": started_at,+ "last_active": started_at, "ended_at": None, "archived": False,+ }+++def test_owned_run_past_the_activity_window_is_scheduler_owned(homes, monkeypatch):+ job_id = "longtool"+ execution = _claim(homes["default"], job_id)+ claimed = _claimed_epoch(execution)+ live = _open_row(job_id, "20260929_120000", claimed + 1)+ zombie = _open_row(job_id, "20260929_110000", claimed - 3600)+ monkeypatch.setattr(_rt_cron.time, "time", lambda: claimed + 1800) # 30 min without a tick++ runs = _runs(monkeypatch, job_id, [live, zombie])++ assert runs[live["id"]]["is_active"] is False # the stale window+ assert runs[live["id"]]["scheduler_owned"] is True # ...but the scheduler still runs it+ # An older never-closed run of the same job predates the live claim: still a zombie.+ assert runs[zombie["id"]]["scheduler_owned"] is False+++def test_run_whose_owner_process_died_is_not_owned(homes, monkeypatch):+ job_id = "crashed"+ execution = _claim(homes["default"], job_id)+ _kill_owner(homes["default"], execution["id"])+ claimed = _claimed_epoch(execution)+ row = _open_row(job_id, "20260929_120000", claimed + 1)++ assert _runs(monkeypatch, job_id, [row])[row["id"]]["scheduler_owned"] is False+++def test_finished_attempt_and_closed_run_are_not_owned(homes, monkeypatch):+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ from cron.executions import finish_execution++ job_id = "done"+ execution = _claim(homes["default"], job_id)+ claimed = _claimed_epoch(execution)+ closed = {**_open_row(job_id, "20260929_130000", claimed + 1), "ended_at": claimed + 60}++ assert _runs(monkeypatch, job_id, [closed])[closed["id"]]["scheduler_owned"] is False++ token = set_hermes_home_override(str(homes["default"]))+ try:+ finish_execution(execution["id"], success=False, error="watchdog")+ finally:+ reset_hermes_home_override(token)+ open_row = _open_row(job_id, "20260929_120000", claimed + 1)++ assert _runs(monkeypatch, job_id, [open_row])[open_row["id"]]["scheduler_owned"] is False+++def test_ownership_reads_the_owner_profiles_ledger(homes, monkeypatch):+ """A→B→A: a live claim in worker_alpha never makes default's run look owned, and back."""+ job_id = "shared-name"+ execution = _claim(homes["worker_alpha"], job_id)+ claimed = _claimed_epoch(execution)+ row = _open_row(job_id, "20260929_120000", claimed + 1)++ assert _runs(monkeypatch, job_id, [row], profile="worker_alpha")[row["id"]]["scheduler_owned"] is True+ assert _runs(monkeypatch, job_id, [row], profile="default")[row["id"]]["scheduler_owned"] is False+ assert _runs(monkeypatch, job_id, [row], profile="worker_alpha")[row["id"]]["scheduler_owned"] is True+++def test_session_detail_stamps_the_same_answer_for_cron_runs_only(homes):+ job_id = "detail"+ execution = _claim(homes["default"], job_id)+ claimed = _claimed_epoch(execution)+ row = _open_row(job_id, "20260929_120000", claimed + 1)++ assert _rt_cron.cron_run_scheduler_owned(row, None) is True+ assert _rt_cron.cron_run_scheduler_owned({**row, "ended_at": claimed + 5}, None) is False+ assert _rt_cron.cron_run_scheduler_owned({**row, "source": "desktop"}, None) is None