Skip to content

The agent that grows with you

fix(gateway): explain read-only cron session failures

Ehsan-hash9bd07143a0c8
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
index f9739d12bd0..becad5594ff 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
@@ -392,6 +392,7 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
payload?.response_previewed,
turnFailure(payload, finalText),
occurredAt,
+ payload?.timestamp,
payload?.persisted_turn,
Boolean(payload?.response_transformed),
typeof payload?.status === 'string' ? payload.status : undefined,
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts
index 0cb8b6e24a3..12435b6450b 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts
@@ -21,6 +21,7 @@ export interface GatewayEventDeps {
responsePreviewed?: boolean,
failure?: { error: string; partial: boolean },
occurredAt?: number,
+ failureAt?: number,
persistedTurn?: PersistedTurn | null,
responseTransformed?: boolean,
status?: string,
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
index 4035aaaa1eb..5c0871c644d 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
@@ -86,6 +86,9 @@ let streamMessageSeq = 0
const nextStreamMessageId = (prefix: string) => `${prefix}-${Date.now()}-${++streamMessageSeq}`
+const validGatewayFailureAt = (failureAt: number | undefined, completionError: string | null): number | undefined =>
+ completionError && typeof failureAt === 'number' && Number.isFinite(failureAt) && failureAt > 0 ? failureAt : undefined
+
/**
* A sealed stream can lose a few characters while the authoritative final
* remains the same reply. Limit the tolerated edit distance so a separate
@@ -740,6 +743,7 @@ export function useMessageStream({
responsePreviewed?: boolean,
failure?: { error: string; partial: boolean; surface?: ErrorSurface | null },
occurredAt = Date.now() / 1000,
+ failureAt?: number,
persistedTurn?: PersistedTurn | null,
responseTransformed?: boolean,
status?: string,
@@ -787,6 +791,8 @@ export function useMessageStream({
? Math.max(1, Math.round((Date.now() - state.turnStartedAt) / 1000))
: undefined
+ const validFailureAt = validGatewayFailureAt(failureAt, completionError)
+
const replaceTextPart = (parts: ChatMessagePart[], interim: boolean) => {
// The backend says every word of this final is already on screen; a
// merge bounded at the last tool row would paint it twice. A bubble
@@ -837,6 +843,7 @@ export function useMessageStream({
interim: false,
recovered: false,
...(durationS !== undefined ? { durationS } : {}),
+ ...(validFailureAt !== undefined ? { failureAt: validFailureAt } : {}),
...(completionError && failure?.surface ? { errorSurface: failure.surface } : {})
}
@@ -867,6 +874,7 @@ export function useMessageStream({
completedAt: occurredAt,
branchGroupId: state.pendingBranchGroup ?? undefined,
...(durationS !== undefined ? { durationS } : {}),
+ ...(validFailureAt !== undefined ? { failureAt: validFailureAt } : {}),
...(completionError && { error: completionError }),
...(completionError && failure?.surface ? { errorSurface: failure.surface } : {})
})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx
index 8ecefe8e090..57a650ca8ae 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx
@@ -77,6 +77,7 @@ describe('terminal error message.complete frames', () => {
const bubble = lastAssistant()
expect(bubble?.error).toBe('Error: something broke')
+ expect(bubble?.failureAt).toBeUndefined()
})
it('attaches the structured error_surface descriptor to the failed bubble', async () => {
@@ -96,6 +97,23 @@ describe('terminal error message.complete frames', () => {
expect(bubble?.errorSurface).toEqual({ layer: 'provider', code: 'rate_limit', retryable: true })
})
+ it('uses the gateway terminal timestamp for the failed bubble', async () => {
+ mountStream()
+ await start()
+
+ await completeWithError({
+ timestamp: 123.5,
+ text: 'This session belongs to a scheduled run and cannot accept your message. Start a new chat to send it.',
+ error: 'This session belongs to a scheduled run and cannot accept your message. Start a new chat to send it.',
+ error_surface: { layer: 'gateway', code: 'cron_session_read_only', retryable: false }
+ })
+
+ const bubble = lastAssistant()
+ expect(bubble?.completedAt).toBe(123.5)
+ expect(bubble?.failureAt).toBe(123.5)
+ expect(bubble?.errorSurface).toEqual({ layer: 'gateway', code: 'cron_session_read_only', retryable: false })
+ })
+
it('ignores a garbled error_surface payload (older/foreign backends)', async () => {
mountStream()
await start()
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index c77ff0cfd89..638b44c1514 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -254,9 +254,8 @@ const COMPARED_FIELDS = [
'reactions',
'timestamp',
'completedAt',
- // Turn wall-clock duration — stamps the visible "⏱ 38s" badge, so a change
- // must re-render (set once at completion; stable afterwards).
- 'durationS'
+ // Turn duration and gateway failure time drive visible metadata.
+ 'durationS', 'failureAt'
] as const
const IGNORED_FIELDS = ['attachmentRefs', 'parts', 'serverRowSpan'] as const
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
index af59003e690..c2ea5e20049 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
@@ -591,6 +591,13 @@ const useErrorText = () =>
return status?.type === 'incomplete' && typeof status.error === 'string' ? status.error : ''
})
+const useErrorFailureAt = () =>
+ useAuiState(s => {
+ const value = s.message.metadata?.custom?.failureAt
+
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined
+ })
+
const ErrorCardHeadline: FC = () => {
const { t } = useI18n()
const surface = useErrorSurface()
@@ -825,6 +832,7 @@ const ErrorRecoveryActions: FC = () => {
const copy = t.assistant.thread
const surface = useErrorSurface()
const errorText = useErrorText()
+ const failureAt = useErrorFailureAt()
// useNavigate() would throw here when no Router is above us; the deep-link
// children mount only when one is (see SettingsLinkAction).
@@ -910,10 +918,11 @@ const ErrorRecoveryActions: FC = () => {
() =>
formatErrorDiagnostics({
errorText,
+ failureAt,
model: model || undefined,
surface
}),
- [errorText, model, surface]
+ [errorText, failureAt, model, surface]
)
const startNewSession = useCallback(() => {
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index b6834749ee5..16bf0ee35f1 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -4625,16 +4625,16 @@ export const en: Translations = {
body: 'The reply kept repeating the same steps, so Hermes stopped it. Retry, or start a new chat if it happens again.'
},
SESSION_OWNER_BUSY: {
- title: 'Hermes is busy in this chat',
- body: 'Another turn is running here and your message could not join its queue. Nothing was sent. Retry once that turn ends.'
+ title: 'Hermes is busy in this chat', body: 'Another turn is running here and your message could not join its queue. Nothing was sent. Retry once that turn ends.'
+ },
+ cron_session_read_only: {
+ title: 'This is a scheduled session', body: 'This session belongs to a scheduled run and cannot accept your message. Start a new chat to send it.'
},
SESSION_OWNER_UNCONFIRMED: {
- title: 'Your message may already be queued',
- body: 'The gateway did not confirm your message in time. If it was queued, it runs once the earlier turn finishes or is resolved. Check the chat before sending it again.'
+ title: 'Your message may already be queued', body: 'The gateway did not confirm your message in time. If it was queued, it runs once the earlier turn finishes or is resolved. Check the chat before sending it again.'
},
SESSION_NOT_OWNED: {
- title: 'This chat is open somewhere else',
- body: 'This chat is currently open in another Hermes window or terminal. Close it there and send your message again, or start a new chat here.'
+ title: 'This chat is open somewhere else', body: 'This chat is currently open in another Hermes window or terminal. Close it there and send your message again, or start a new chat here.'
},
disk_full: {
title: 'Disk full',
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index 4e10210e454..d873a6ef103 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -61,6 +61,9 @@ export type ChatMessage = {
* stamped by the desktop when it watched the turn run. Absent for
* messages hydrated from history — the backend doesn't persist it. */
durationS?: number
+ /** Gateway-recorded failure epoch. Absent when an older gateway omitted it;
+ * never substitute the Desktop receipt clock for diagnostics. */
+ failureAt?: number
/** Composer attachment ref strings (`@file:...`, `@image:...`) sent with this user message. */
attachmentRefs?: string[]
/** Durable backend `messages.id`. Absent until the row is persisted. */
diff --git a/apps/desktop/src/lib/chat-runtime.ts b/apps/desktop/src/lib/chat-runtime.ts
index 190148142ca..c5d20c08b48 100644
--- a/apps/desktop/src/lib/chat-runtime.ts
+++ b/apps/desktop/src/lib/chat-runtime.ts
@@ -425,6 +425,9 @@ export function messageCreatedAt(message: Pick<ChatMessage, 'timestamp'>, nowMs
: new Date(nowMs)
}
+const failureMetadata = (message: Pick<ChatMessage, 'failureAt'>) =>
+ message.failureAt !== undefined ? { failureAt: message.failureAt } : {}
+
export function toRuntimeMessage(message: ChatMessage): ThreadMessage {
const role =
message.role === 'user' || message.role === 'assistant' || message.role === 'system' ? message.role : 'assistant'
@@ -493,6 +496,7 @@ export function toRuntimeMessage(message: ChatMessage): ThreadMessage {
...(message.interrupted ? { interrupted: true } : {}),
...timelineMeta,
...(message.completedAt !== undefined ? { timelineCompletedAt: message.completedAt } : {}),
+ ...failureMetadata(message),
...(message.durationS !== undefined ? { durationS: message.durationS } : {}),
// Structured failure layer for the error card (see lib/error-surface).
...(message.errorSurface ? { errorSurface: message.errorSurface } : {}),
diff --git a/apps/desktop/src/lib/error-surface.test.ts b/apps/desktop/src/lib/error-surface.test.ts
index 39800109de1..4087122b493 100644
--- a/apps/desktop/src/lib/error-surface.test.ts
+++ b/apps/desktop/src/lib/error-surface.test.ts
@@ -77,9 +77,20 @@ describe('formatErrorDiagnostics', () => {
const text = formatErrorDiagnostics({ errorText: 'boom' })
expect(text).not.toContain('layer:')
+ expect(text).not.toContain('time:')
expect(text).not.toContain('model:')
expect(text.split('\n').every(line => line.trim().length > 0)).toBe(true)
})
+
+ it('uses the gateway failure timestamp when one is present', () => {
+ const text = formatErrorDiagnostics({ errorText: 'boom', failureAt: 1792345678.25 })
+
+ expect(text).toContain(`time: ${new Date(1792345678.25 * 1000).toISOString()}`)
+ })
+
+ it('omits an out-of-range gateway timestamp', () => {
+ expect(formatErrorDiagnostics({ errorText: 'boom', failureAt: Number.MAX_VALUE })).not.toContain('time:')
+ })
})
// The card body and the buttons under it must agree: a body that says "retry"
@@ -188,6 +199,17 @@ describe('free-tier refusals', () => {
})
})
+describe('cron admission conflicts', () => {
+ it('uses scheduled-session copy and starts a new chat instead of retrying', () => {
+ const surface = parseErrorSurface({ layer: 'gateway', code: 'cron_session_read_only', retryable: false })!
+ const { body, title } = errorCardText(en.assistant.thread, surface)
+
+ expect(title).toBe(en.assistant.thread.errorCodes.cron_session_read_only.title)
+ expect(body).toBe(en.assistant.thread.errorCodes.cron_session_read_only.body)
+ expect(errorRecoveryPlan(surface)).toMatchObject({ retry: false, startNewSession: true })
+ })
+})
+
describe('limit reset (#98852)', () => {
it('parses resets_at and renders "HH:mm (in Nh MMm)" while the reset is ahead', () => {
const now = Date.UTC(2026, 0, 1, 12, 0, 0)
diff --git a/apps/desktop/src/lib/error-surface.ts b/apps/desktop/src/lib/error-surface.ts
index 5950e89bf8f..dd54265cce2 100644
--- a/apps/desktop/src/lib/error-surface.ts
+++ b/apps/desktop/src/lib/error-surface.ts
@@ -51,6 +51,8 @@ export const ERROR_CODE_KEYS = [
'SESSION_NOT_OWNED',
// The gateway that owns the chat is mid-turn and could not queue this send: transient.
'SESSION_OWNER_BUSY',
+ // Cron sessions are durable scheduled-run sessions and cannot accept ordinary chat input.
+ 'cron_session_read_only',
// The owner did not confirm a forwarded send in time; it may already be queued: no Retry.
'SESSION_OWNER_UNCONFIRMED',
'disk_full',
@@ -272,6 +274,7 @@ const SWITCH_PROVIDER_LAYERS: readonly ErrorSurfaceLayer[] = ['auth', 'billing',
const CODE_PLANS: Partial<Record<ErrorCodeKey, Partial<ErrorRecoveryPlan>>> = {
SESSION_NOT_OWNED: { retry: false, startNewSession: true },
SESSION_OWNER_BUSY: { retry: true, startNewSession: false },
+ cron_session_read_only: { retry: false, startNewSession: true },
SESSION_OWNER_UNCONFIRMED: { retry: false, startNewSession: false },
content_policy_blocked: { editMessage: true, retry: false },
context_overflow: { compress: true, retry: false, startNewSession: true },
@@ -311,6 +314,8 @@ export function errorRecoveryPlan(surface: ErrorSurface | null | undefined): Err
export function formatErrorDiagnostics(input: {
appVersion?: string
errorText: string
+ /** Epoch seconds when the gateway recorded the failure. Absent on legacy frames. */
+ failureAt?: number
model?: string
provider?: string
surface?: ErrorSurface | null
@@ -319,10 +324,14 @@ export function formatErrorDiagnostics(input: {
// caller-supplied fallback (typically the foreground composer's atoms).
const provider = input.surface?.provider || input.provider
const model = input.surface?.model || input.model
+ const failureAt = input.failureAt
+ const hasFailureAt = typeof failureAt === 'number' && Number.isFinite(failureAt) && failureAt > 0
+ const failureDate = hasFailureAt ? new Date(failureAt * 1000) : null
+ const failureTime = failureDate && Number.isFinite(failureDate.getTime()) ? failureDate.toISOString() : null
const lines = [
'── Hermes error details ──',
- `time: ${new Date().toISOString()}`,
+ failureTime ? `time: ${failureTime}` : null,
input.surface ? `layer: ${input.surface.layer}` : null,
input.surface ? `code: ${input.surface.code}` : null,
input.surface ? `retryable: ${input.surface.retryable}` : null,
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 811f61b191a..0155fb1baa0 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -5615,6 +5615,7 @@ export interface MessageInterimPayload {
/** ``prompt_turn._complete_turn_payload`` / ``session_auto_continue._emit_terminal_turn_error`` / ``agent_callbacks._mirror_subagent_to_child`` (child watch mirror: ``text`` only) / ``compute_host_bridge`` (``text`` + ``status``). */
export interface MessageCompletePayload {
text?: string | unknown
+ timestamp?: number | null
usage?: Usage | null
status?: TurnStatus | null
reasoning?: string | null
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index bf0e80e9f20..64e5cbce5d3 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -23466,6 +23466,18 @@
"default": "",
"title": "Text"
},
+ "timestamp": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Timestamp"
+ },
"usage": {
"anyOf": [
{
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index fe9edf5be5c..5917d8232c0 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -11,6 +11,7 @@ from contextvars import ContextVar
from dataclasses import asdict, dataclass, field
from functools import partial
import sqlite3
+import time
from types import SimpleNamespace
import uuid
@@ -39,6 +40,14 @@ native_write_started = ContextVar('native_write_started', default=False)
# while acceptance itself still waits for the commit.
messaging_admission = ContextVar('messaging_admission', default=None)
+_CRON_ADMISSION_CONFLICT_TEXT = (
+ 'This session belongs to a scheduled run and cannot accept your message. '
+ 'Start a new chat to send it.'
+)
+_CRON_ADMISSION_CONFLICT_SURFACE = {
+ 'layer': 'gateway', 'code': 'cron_session_read_only', 'retryable': False,
+}
+
@dataclass
class LiveSession:
@@ -1170,6 +1179,31 @@ class SessionAuthority:
return None, 'settled_unknown'
self._pause(ref, 'unknown_execution')
raise
+ except RuntimeStoreError as exc:
+ if exc.reason == 'admission_conflict':
+ try:
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(self.runner, live.source)
+ except (RuntimeStoreError, AttributeError):
+ policy = None
+ if policy is not None and policy.source == 'cron':
+ failure_at = time.time()
+ self.pending_results[row['admission_id']] = {
+ 'result': {
+ 'final_response': '',
+ 'messages': [],
+ 'failed': True,
+ 'completed': False,
+ 'error': _CRON_ADMISSION_CONFLICT_TEXT,
+ 'error_surface': dict(_CRON_ADMISSION_CONFLICT_SURFACE),
+ 'failure_at': failure_at,
+ },
+ 'usage': {},
+ }
+ return _CRON_ADMISSION_CONFLICT_TEXT, 'failed'
+ import logging
+ logging.getLogger(__name__).exception('Admitted turn %s failed', row['admission_id'])
+ return 'The admitted turn failed.', 'failed'
except Exception:
import logging
logging.getLogger(__name__).exception('Admitted turn %s failed', row['admission_id'])
diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.py
index bec411d9f99..48d6a0f3ca6 100644
--- a/gateway/session_settlement_recovery.py
+++ b/gateway/session_settlement_recovery.py
@@ -1,6 +1,7 @@
"""Fence an unsettled claim in a live owner without inventing a terminal result."""
import asyncio
import logging
+import math
import sqlite3
from hermes_state_runtime import RuntimeStoreError, _admission, _epoch, settle_steer_transfers
@@ -61,6 +62,22 @@ def completion_payload(row, settled, response, captured):
# Only the agent's reuse site sets this (never inferred from equal text): the
# final repeats a reply the viewer already painted, so it settles in place.
captured_result = (captured or {}).get('result') or {}
+ # This is the one gateway-owned failure descriptor that is safe to echo to the client. Other
+ # captured error strings can contain provider details, so they stay behind the persisted result
+ # boundary and do not become a live error card by accident.
+ error_surface = captured_result.get('error_surface')
+ if (isinstance(error_surface, dict)
+ and error_surface.get('layer') == 'gateway'
+ and error_surface.get('code') == 'cron_session_read_only'
+ and error_surface.get('retryable') is False
+ and isinstance(captured_result.get('error'), str)
+ and captured_result['error']):
+ complete['error'] = captured_result['error']
+ complete['error_surface'] = dict(error_surface)
+ failure_at = captured_result.get('failure_at')
+ if (isinstance(failure_at, (int, float)) and not isinstance(failure_at, bool)
+ and math.isfinite(failure_at) and failure_at > 0):
+ complete['timestamp'] = failure_at
if response and captured_result.get('response_reused'):
complete['response_reused'] = True
if captured_result.get('local_viewer'):
diff --git a/tests/gateway/test_cron_admission_error_surface.py b/tests/gateway/test_cron_admission_error_surface.py
new file mode 100644
index 00000000000..c057c195ed9
--- /dev/null
+++ b/tests/gateway/test_cron_admission_error_surface.py
@@ -0,0 +1,176 @@
+"""Cron admission conflicts keep a safe, actionable terminal error."""
+from __future__ import annotations
+
+import json
+import threading
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_state_runtime import RuntimeStoreError
+
+
+def _claimed():
+ authority = SimpleNamespace(
+ runner=SimpleNamespace(),
+ pending_results={},
+ executing={"session-1": object()},
+ )
+ live = SimpleNamespace(
+ source=SimpleNamespace(),
+ event_stream=SimpleNamespace(lock=threading.RLock()),
+ )
+ ref = SimpleNamespace(session_id="session-1")
+ row = {"admission_id": "admission-1", "payload": {"text": "hello"}}
+ return authority, live, ref, row
+
+
+async def test_cron_admission_conflict_preserves_actionable_result(monkeypatch):
+ from gateway import session_finite, session_policy
+ from gateway import session_authority
+ from gateway.session_authority import SessionAuthority
+
+ async def fail(*_args):
+ raise RuntimeStoreError("admission_conflict")
+
+ monkeypatch.setattr(session_finite, "execute_finite_admission", fail)
+ monkeypatch.setattr(session_policy, "policy_for_source", lambda *_args: SimpleNamespace(source="cron"))
+ monkeypatch.setattr(time, "time", lambda: 123.5)
+ authority, live, ref, row = _claimed()
+
+ response, outcome = await SessionAuthority._execute_claimed(authority, ref, live, row)
+
+ assert outcome == "failed"
+ assert response == "This session belongs to a scheduled run and cannot accept your message. Start a new chat to send it."
+ assert authority.pending_results[row["admission_id"]]["result"] == {
+ "final_response": "",
+ "messages": [],
+ "failed": True,
+ "completed": False,
+ "error": response,
+ "error_surface": {"layer": "gateway", "code": "cron_session_read_only", "retryable": False},
+ "failure_at": 123.5,
+ }
+
+
+async def test_same_message_after_terminal_cron_admission_is_rejected_without_running_job(owner, monkeypatch):
+ from gateway import session_authority
+ from gateway.config import Platform
+ from gateway.session import SessionSource
+ from gateway.session_authority import SessionAuthority
+ from gateway.session_contract import SessionRef
+ from gateway.session_local import LocalSessionAdapter
+ from hermes_state_runtime import admit_session_input, claim_session_input, settle_session_input
+
+ session_id = "cron-guard-session"
+ owner.db.create_session(session_id, source="local")
+ admit_session_input(owner.db, epoch=owner.epoch, principal_id="cron-user", session_id=session_id,
+ request_id="request-1", payload={"text": "expected"})
+ original = claim_session_input(owner.db, epoch=owner.epoch, session_id=session_id)
+ settle_session_input(owner.db, epoch=owner.epoch, admission_id=original["admission_id"],
+ generation=original["generation"], outcome="completed")
+ admit_session_input(owner.db, epoch=owner.epoch, principal_id="cron-user", session_id=session_id,
+ request_id="request-2", payload={"text": "expected"})
+ row = claim_session_input(owner.db, epoch=owner.epoch, session_id=session_id)
+ source = SessionSource(platform=Platform.LOCAL, chat_id=session_id, user_id="cron-user", profile="default")
+ live = SimpleNamespace(source=source, event_stream=SimpleNamespace(lock=threading.RLock()))
+ owner.sessions[session_id] = live
+ adapter = LocalSessionAdapter(owner)
+ adapter.register_source(source)
+ owner.runner._adapter_for_source = lambda _source: adapter
+ adapter.policies[session_id] = SimpleNamespace(
+ source="cron",
+ request_json=json.dumps({
+ "cron_job": {"id": "job-1"}, "extra_prompt": "expected", "request_id": "request-1",
+ }),
+ )
+ run_calls = []
+
+ def run_job(*args, **kwargs):
+ run_calls.append((args, kwargs))
+ raise AssertionError("cron run_job must not run after the admission guard rejects the payload")
+
+ from cron import scheduler
+
+ monkeypatch.setattr(scheduler, "run_job", run_job)
+ monkeypatch.setattr(time, "time", lambda: 123.5)
+ response, outcome = await SessionAuthority._execute_claimed(
+ owner, SessionRef("default", session_id), live, row)
+
+ assert (response, outcome) == (
+ "This session belongs to a scheduled run and cannot accept your message. Start a new chat to send it.",
+ "failed",
+ )
+ assert run_calls == []
+ assert owner.pending_results[row["admission_id"]]["result"]["failure_at"] == 123.5
+
+
+async def test_unexpected_admission_failure_stays_generic(monkeypatch):
+ from gateway import session_finite, session_policy
+ from gateway.session_authority import SessionAuthority
+
+ async def fail(*_args):
+ raise RuntimeStoreError("admission_conflict")
+
+ monkeypatch.setattr(session_finite, "execute_finite_admission", fail)
+ monkeypatch.setattr(session_policy, "policy_for_source", lambda *_args: SimpleNamespace(source="cli"))
+ authority, live, ref, row = _claimed()
+
+ response, outcome = await SessionAuthority._execute_claimed(authority, ref, live, row)
+
+ assert (response, outcome) == ("The admitted turn failed.", "failed")
+ assert authority.pending_results == {}
+
+
+def test_completion_forwards_only_safe_cron_error_metadata():
+ from gateway.session_settlement_recovery import completion_payload
+
+ row = {"admission_id": "admission-1", "request_id": "request-1"}
+ captured = {
+ "result": {
+ "error": "This session belongs to a scheduled run and cannot accept your message. Start a new chat to send it.",
+ "error_surface": {"layer": "gateway", "code": "cron_session_read_only", "retryable": False},
+ "failure_at": 123.5,
+ }
+ }
+
+ complete = completion_payload(row, {"outcome": "failed"}, captured["result"]["error"], captured)
+
+ assert complete["error"] == captured["result"]["error"]
+ assert complete["error_surface"] == captured["result"]["error_surface"]
+ assert complete["timestamp"] == 123.5
+
+
+def test_saved_result_keeps_failure_time_for_reopened_admission(owner):
+ from gateway.session_results import admission_result, finish_result
+ from gateway.session_settlement_recovery import completion_payload
+ from hermes_state_runtime import admit_session_input, claim_session_input
+
+ owner.db.create_session("cron", source="local")
+ admit_session_input(owner.db, epoch=owner.epoch, principal_id="cron", session_id="cron",
+ request_id="request-1", payload={"text": "hello"})
+ row = claim_session_input(owner.db, epoch=owner.epoch, session_id="cron")
+ captured = {
+ "result": {
+ "final_response": "",
+ "messages": [],
+ "failed": True,
+ "completed": False,
+ "error": "This session belongs to a scheduled run and cannot accept your message. Start a new chat to send it.",
+ "error_surface": {"layer": "gateway", "code": "cron_session_read_only", "retryable": False},
+ "failure_at": 123.5,
+ },
+ "usage": {},
+ }
+
+ finish_result(owner.db, epoch=owner.epoch, row=row, response=captured["result"]["error"],
+ outcome="failed", result=captured)
+
+ reopened = admission_result(owner.db, row["admission_id"])
+ assert reopened["result"]["failure_at"] == 123.5
+ complete = completion_payload(row, {"outcome": "failed"}, reopened["result"]["error"], reopened)
+ assert complete["timestamp"] == 123.5
diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.py
index b44328f5f04..6cf08104fe4 100644
--- a/tui_gateway/contracts/events.py
+++ b/tui_gateway/contracts/events.py
@@ -240,6 +240,9 @@ class MessageCompletePayload(Payload):
``compute_host_bridge`` (``text`` + ``status``)."""
text: str | JsonValue = ""
+ #: Epoch seconds when the gateway recorded this terminal outcome. Older gateways omit it;
+ #: clients must keep their legacy receipt-time fallback for those frames.
+ timestamp: float | None = None
usage: Usage | None = None
status: TurnStatus | None = None
reasoning: str | None = None