Skip to content

The agent that grows with you

fix(cron): keep failed fires and the Desktop write gate after review

unsupportedpastelsa13f5bb8c23a
diff --git a/apps/desktop/src/app/cron/open-cron-run.test.ts b/apps/desktop/src/app/cron/open-cron-run.test.ts
index 5342b9c75b0..0ebe6ab07e8 100644
--- a/apps/desktop/src/app/cron/open-cron-run.test.ts
+++ b/apps/desktop/src/app/cron/open-cron-run.test.ts
@@ -4,7 +4,13 @@ import { $cronRunReadOnlyVerdicts, isStoredTranscriptReadOnly } from '@/store/re
import { $cronSessions, $sessions } from '@/store/session'
import type { SessionInfo } from '@/types/hermes'
-import { isResumableCronRun, openCronRun, reconcileCronRunVerdicts, refreshCronRunWriteGate } from './open-cron-run'
+import {
+ cronRunWriteGateApplies,
+ isResumableCronRun,
+ openCronRun,
+ reconcileCronRunVerdicts,
+ refreshCronRunWriteGate
+} from './open-cron-run'
const NOW_MS = 1_800_000_000_000
const NOW_S = NOW_MS / 1000
@@ -180,8 +186,20 @@ describe('refreshCronRunWriteGate — a unified-runtime run is known by its row,
expect(isStoredTranscriptReadOnly(id)).toBe(true)
})
+ it('keeps gating an opened run after a sidebar refresh drops its row from the cache', async () => {
+ $cronSessions.set([cachedRow('cron')])
+ openCronRun({ ...cachedRow('cron'), scheduler_owned: true }, vi.fn()) // opened live: writable
+ $cronSessions.set([]) // the latest page no longer lists it
+ const fetchRow = vi.fn(async () => ({ ended_at: null, last_active: 0, scheduler_owned: false, source: 'cron' }))
+
+ expect(cronRunWriteGateApplies(id)).toBe(true)
+ expect(await refreshCronRunWriteGate(id, fetchRow)).toBe(true) // its scheduler died since
+ expect(fetchRow).toHaveBeenCalledWith(id)
+ })
+
it('never fetches for an ordinary session that also has a local id', async () => {
$sessions.set([cachedRow('desktop')])
+ expect(cronRunWriteGateApplies(id)).toBe(false)
const fetchRow = vi.fn()
expect(await refreshCronRunWriteGate(id, fetchRow)).toBe(false)
diff --git a/apps/desktop/src/app/cron/open-cron-run.ts b/apps/desktop/src/app/cron/open-cron-run.ts
index 67d970fda37..c958a39ad2d 100644
--- a/apps/desktop/src/app/cron/open-cron-run.ts
+++ b/apps/desktop/src/app/cron/open-cron-run.ts
@@ -78,6 +78,18 @@ export function isCronRunSession(storedSessionId: null | string | undefined): bo
return isCronRunRow(cached) || LEGACY_CRON_RUN_SESSION_ID.test(id)
}
+/**
+ * Whether a send to this session must re-check the cron write gate: it is a
+ * cron run by its cached row or legacy id, or a verdict was recorded when it
+ * was opened. The verdict keeps a `local-*` run gated after a sidebar refresh
+ * drops its row from the cached list.
+ */
+export function cronRunWriteGateApplies(storedSessionId: null | string | undefined): boolean {
+ const id = storedSessionId?.trim()
+
+ return Boolean(id) && (isCronRunSession(id) || hasCronRunVerdict(id))
+}
+
function recordRunVerdict(run: CronRunRow): void {
recordCronRunVerdict(run.id, !isResumableCronRun(run))
}
@@ -129,7 +141,7 @@ export async function refreshCronRunWriteGate(
): Promise<boolean> {
const id = storedSessionId?.trim()
- if (!id || !(isCronRunSession(id) || hasCronRunVerdict(id))) {
+ if (!id || !cronRunWriteGateApplies(id)) {
return false
}
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.ts
index 773b5caf08f..64369f07f44 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
@@ -26,7 +26,7 @@ import { $hudMode } from '@/store/hud'
import { clearNotifications, notify, notifyError } from '@/store/notifications'
import { consumePendingCredentialWarning, requestDesktopOnboarding } from '@/store/onboarding'
import { trackPendingSubmission } from '@/store/pending-submissions'
-import { isCronRunReadOnly, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'
+import { isStoredTranscriptReadOnly } from '@/store/read-only-transcript'
import {
$activeSessionId,
$sessions,
@@ -41,7 +41,7 @@ import { profileScopeForSessionOwner } from '@/store/session-request-router'
import { $sessionStates, $sessionTiles } from '@/store/session-states'
import type { SessionInfo } from '@/types/hermes'
-import { isCronRunSession, refreshCronRunWriteGate } from '../../../cron/open-cron-run'
+import { cronRunWriteGateApplies, 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'
@@ -328,7 +328,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
// 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 (isCronRunSession(targetStoredSessionId) || isCronRunReadOnly(targetStoredSessionId)) {
+ if (cronRunWriteGateApplies(targetStoredSessionId)) {
const viewBeforeGate = selectedStoredSessionIdRef.current
await refreshCronRunWriteGate(targetStoredSessionId, id =>
diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.py
index 3992b9309ea..7effaeb01f4 100644
--- a/hermes_cli/web_routers/cron.py
+++ b/hermes_cli/web_routers/cron.py
@@ -585,9 +585,10 @@ def _reconcile_cron_runs(
inside the time window (one that failed before it created a session) keeps
its own row. An output doc never records its execution, only a window guess
(``_execution_candidates``), so it pairs by time: a doc within
- ``_SESSION_DOC_MATCH_SECONDS`` of a legacy session, or of a session whose
- execution is one of its candidates, is that session's execution (a doc no
- attempt claims is matched against every session). Doc rows matching no
+ ``_SESSION_DOC_MATCH_SECONDS`` of a legacy session, or of the session whose
+ execution is its likeliest writer (the newest candidate, whose ledger row the
+ doc already stands in for), is that session's execution (a doc no attempt
+ claims is matched against every session). Doc rows matching no
session are distinct executions — script-only fires — and are kept. A session
row must never be dropped in favor of a doc: the doc is the fallback
representation.
@@ -601,7 +602,10 @@ def _reconcile_cron_runs(
candidates = doc.get("_execution_candidates")
execution_id = doc.get("_execution_id")
if candidates:
- window = legacy + [s for s in session_runs if s.get("cron_execution_id") in candidates]
+ # The likeliest writer is the doc's newest candidate, the attempt _list_cron_output_runs
+ # folded into it. When no unified session names that attempt, the doc is its only row:
+ # only a legacy session can still claim it by time.
+ window = legacy + [s for s in session_runs if s.get("cron_execution_id") == candidates[0]]
elif candidates is None and execution_id:
if execution_id in executions:
continue
diff --git a/tests/hermes_cli/test_cron_run_history_sessions.py b/tests/hermes_cli/test_cron_run_history_sessions.py
index 3f6d7a0fa04..857f2500998 100644
--- a/tests/hermes_cli/test_cron_run_history_sessions.py
+++ b/tests/hermes_cli/test_cron_run_history_sessions.py
@@ -9,6 +9,7 @@ through the real routes in a temp default profile.
"""
from datetime import timedelta
from types import SimpleNamespace
+from zoneinfo import ZoneInfo
import pytest
@@ -44,6 +45,11 @@ def owner(tmp_path, monkeypatch):
epoch=begin_runtime_epoch(db, instance_id='test'))
monkeypatch.setattr(authority, '_schedule', lambda ref: None)
runner.session_authority = authority
+ # Pin the configured zone so the output writer and the run-history reader resolve the same
+ # one, whatever the process's C-level zone (conftest sets TZ=UTC in the env without tzset).
+ utc = ZoneInfo('UTC')
+ monkeypatch.setattr(hermes_time, 'get_timezone', lambda: utc)
+ monkeypatch.setattr(cron_routes, '_get_timezone', lambda: utc)
yield authority
db.close()
@@ -131,7 +137,8 @@ async def test_detail_still_recognises_legacy_runs_and_leaves_other_sessions_alo
@pytest.mark.asyncio
-async def test_a_fire_that_failed_beside_a_unified_run_keeps_its_own_row(owner, clock):
[email protected]('failed_fire_wrote_doc', [False, True])
+async def test_a_fire_that_failed_beside_a_unified_run_keeps_its_own_row(owner, clock, failed_fire_wrote_doc):
"""Output rows pair with sessions per execution: the next fire failing a minute later, before
it created a session, is its own run, not swallowed by its neighbour's time window."""
job = jobs.create_job(prompt='report', schedule='every 1m', deliver='local')['id']
@@ -144,12 +151,17 @@ async def test_a_fire_that_failed_beside_a_unified_run_keeps_its_own_row(owner,
second = executions.create_execution(job, source='test')['id']
executions.mark_execution_running(second)
clock['seconds'] = 70
+ if failed_fire_wrote_doc:
+ # Its doc also falls in the first run's grace window: it must stay the failed fire's row.
+ jobs.save_job_output(job, '# Cron Job: report\n\nscript failed')
executions.finish_execution(second, success=False, error='owner_unavailable')
runs = _runs(job)
- assert [r['source'] for r in runs] == ['cron_output', 'cron']
- assert runs[0]['title'].startswith('FAILED') and runs[0]['preview'] == 'owner_unavailable'
+ assert [r['source'] for r in runs] == ['cron_output', 'cron'], runs
+ assert runs[0]['title'].startswith('FAILED')
+ if not failed_fire_wrote_doc:
+ assert runs[0]['preview'] == 'owner_unavailable'
assert (runs[1]['id'], runs[1]['cron_execution_id']) == (session_id, first)