The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: a message typed into a running cron chat says why it was refused (#141348)
Teknium165a2f01499d
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.tsindex becad5594ff..f9739d12bd0 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,7 +392,6 @@ 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.tsindex 12435b6450b..0cb8b6e24a3 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,7 +21,6 @@ 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.tsindex 5c0871c644d..4035aaaa1eb 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,9 +86,6 @@ let streamMessageSeq = 0const 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@@ -743,7 +740,6 @@ 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,@@ -791,8 +787,6 @@ 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@@ -843,7 +837,6 @@ export function useMessageStream({interim: false,recovered: false,...(durationS !== undefined ? { durationS } : {}),- ...(validFailureAt !== undefined ? { failureAt: validFailureAt } : {}),...(completionError && failure?.surface ? { errorSurface: failure.surface } : {})}@@ -874,7 +867,6 @@ 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.tsxindex 57a650ca8ae..8ecefe8e090 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,7 +77,6 @@ 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 () => {@@ -97,23 +96,6 @@ 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.tsindex 638b44c1514..c77ff0cfd89 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,8 +254,9 @@ const COMPARED_FIELDS = ['reactions','timestamp','completedAt',- // Turn duration and gateway failure time drive visible metadata.- 'durationS', 'failureAt'+ // Turn wall-clock duration — stamps the visible "⏱ 38s" badge, so a change+ // must re-render (set once at completion; stable afterwards).+ 'durationS'] as constconst IGNORED_FIELDS = ['attachmentRefs', 'parts', 'serverRowSpan'] as constdiff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsxindex c2ea5e20049..3cfe0a417e0 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx@@ -591,11 +591,14 @@ const useErrorText = () =>return status?.type === 'incomplete' && typeof status.error === 'string' ? status.error : ''})-const useErrorFailureAt = () =>+// When the failure was recorded: the settled bubble's completion (the terminal frame's time), else the+// row's own timestamp for a hydrated card. Never `createdAt`, whose fallback is render time.+const useErrorFailedAt = () =>useAuiState(s => {- const value = s.message.metadata?.custom?.failureAt+ const custom = s.message.metadata?.custom as { timelineCompletedAt?: unknown; timelineTimestamp?: unknown }+ const at = custom?.timelineCompletedAt ?? custom?.timelineTimestamp- return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined+ return typeof at === 'number' && Number.isFinite(at) && at > 0 ? at : undefined})const ErrorCardHeadline: FC = () => {@@ -832,7 +835,7 @@ const ErrorRecoveryActions: FC = () => {const copy = t.assistant.threadconst surface = useErrorSurface()const errorText = useErrorText()- const failureAt = useErrorFailureAt()+ const failedAt = useErrorFailedAt()// useNavigate() would throw here when no Router is above us; the deep-link// children mount only when one is (see SettingsLinkAction).@@ -918,11 +921,11 @@ const ErrorRecoveryActions: FC = () => {() =>formatErrorDiagnostics({errorText,- failureAt,+ failedAt,model: model || undefined,surface}),- [errorText, failureAt, model, surface]+ [errorText, failedAt, model, surface])const startNewSession = useCallback(() => {diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 16bf0ee35f1..ac39e143900 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -8,6 +8,7 @@ import { enClarify } from './en_clarify'import { enConnectorAccounts } from './en_connector_accounts'import { enConnectorCard } from './en_connector_card'import { enGatewayGroupOpen, enSkillDeepLink } from './en_deep_links'+import { enErrorLayers } from './en_error_layers'import { enFirstRun } from './en_first_run'import { enLocalModels } from './en_local_models'import { enModelMenu } from './en_model_menu'@@ -4502,31 +4503,7 @@ export const en: Translations = {react: 'React',dismissError: 'Dismiss error',responseStopped: 'Response stopped',- errorLayers: {- auth: 'Sign-in problem',- billing: 'Out of credits',- disk: 'Disk full',- endpoint: "Can't reach your model server",- gateway: 'Hermes hit a problem',- generic: "Hermes couldn't finish this reply",- provider: 'The AI service returned an error',- runtime: 'Hermes hit a problem',- streaming: 'The reply was cut off'- },- errorLayerBodies: {- auth: 'The AI service rejected your sign-in. Check the credentials for this provider, then send your message again.',- billing: 'Your account has no credits left for this provider. Top up or switch provider, then send again.',- disk: 'Your disk is full, so Hermes could not save this conversation. Free some space, then retry.',- endpoint:- "Hermes can't reach your custom model server. Check that it is running, then send your message again.",- gateway:- 'Hermes hit an internal problem starting this reply. Send your message again; if it keeps happening, send diagnostics.',- generic: 'Something went wrong while Hermes was replying. Retry, or copy the details if it keeps happening.',- provider: 'The AI service could not complete this request. Retry in a moment or switch provider.',- runtime:- 'Hermes hit an internal problem starting this reply. Send your message again; if it keeps happening, send diagnostics.',- streaming: 'The connection dropped before the reply finished. Retry to send it again.'- },+ ...enErrorLayers,errorCodes: {auth: {title: provider => `${provider} rejected your sign-in`,@@ -4625,16 +4602,20 @@ 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.'+ title: 'This chat belongs to a scheduled job',+ body: 'It only runs that job, so your message was not run. 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/i18n/en_error_layers.ts b/apps/desktop/src/i18n/en_error_layers.tsnew file mode 100644index 00000000000..ac3e084b4a7--- /dev/null+++ b/apps/desktop/src/i18n/en_error_layers.ts@@ -0,0 +1,31 @@+import type { Translations } from './types'++type ThreadCopy = Translations['assistant']['thread']++// The error card's layer fallbacks (lib/error-surface-copy.ts): used when a failure code has no own entry.+export const enErrorLayers: Pick<ThreadCopy, 'errorLayerBodies' | 'errorLayers'> = {+ errorLayers: {+ auth: 'Sign-in problem',+ billing: 'Out of credits',+ disk: 'Disk full',+ endpoint: "Can't reach your model server",+ gateway: 'Hermes hit a problem',+ generic: "Hermes couldn't finish this reply",+ provider: 'The AI service returned an error',+ runtime: 'Hermes hit a problem',+ streaming: 'The reply was cut off'+ },+ errorLayerBodies: {+ auth: 'The AI service rejected your sign-in. Check the credentials for this provider, then send your message again.',+ billing: 'Your account has no credits left for this provider. Top up or switch provider, then send again.',+ disk: 'Your disk is full, so Hermes could not save this conversation. Free some space, then retry.',+ endpoint: "Hermes can't reach your custom model server. Check that it is running, then send your message again.",+ gateway:+ 'Hermes hit an internal problem starting this reply. Send your message again; if it keeps happening, send diagnostics.',+ generic: 'Something went wrong while Hermes was replying. Retry, or copy the details if it keeps happening.',+ provider: 'The AI service could not complete this request. Retry in a moment or switch provider.',+ runtime:+ 'Hermes hit an internal problem starting this reply. Send your message again; if it keeps happening, send diagnostics.',+ streaming: 'The connection dropped before the reply finished. Retry to send it again.'+ }+}diff --git a/apps/desktop/src/i18n/overlay-gaps.json b/apps/desktop/src/i18n/overlay-gaps.jsonindex 8b0c8ee7d7b..f3b0cf7f2e4 100644--- a/apps/desktop/src/i18n/overlay-gaps.json+++ b/apps/desktop/src/i18n/overlay-gaps.json@@ -66,6 +66,8 @@"assistant.thread.errorCodes.content_policy_blocked.title": ["ar","ru"],"assistant.thread.errorCodes.context_overflow.body": ["ar","ja","ru","zh","zh-hant"],"assistant.thread.errorCodes.context_overflow.title": ["ar","ja","ru","zh","zh-hant"],+ "assistant.thread.errorCodes.cron_session_read_only.body": ["ar","de","es","fr","ja","ru","zh","zh-hant"],+ "assistant.thread.errorCodes.cron_session_read_only.title": ["ar","de","es","fr","ja","ru","zh","zh-hant"],"assistant.thread.errorCodes.disk_full.body": ["ar","ja","ru","zh","zh-hant"],"assistant.thread.errorCodes.disk_full.title": ["ar","ja","ru","zh","zh-hant"],"assistant.thread.errorCodes.empty_response.body": ["ar","ru"],diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.tsindex d873a6ef103..4e10210e454 100644--- a/apps/desktop/src/lib/chat-messages/types.ts+++ b/apps/desktop/src/lib/chat-messages/types.ts@@ -61,9 +61,6 @@ 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.tsindex c5d20c08b48..190148142ca 100644--- a/apps/desktop/src/lib/chat-runtime.ts+++ b/apps/desktop/src/lib/chat-runtime.ts@@ -425,9 +425,6 @@ 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'@@ -496,7 +493,6 @@ 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.tsindex 4087122b493..25bfeef53c0 100644--- a/apps/desktop/src/lib/error-surface.test.ts+++ b/apps/desktop/src/lib/error-surface.test.ts@@ -73,24 +73,20 @@ describe('formatErrorDiagnostics', () => {expect(text).not.toContain('some/other-model')})+ it('stamps the recorded failure time, never the copy time (#141348)', () => {+ expect(formatErrorDiagnostics({ errorText: 'boom', failedAt: 1_792_000_000 })).toContain(+ 'time: 2026-10-14T17:46:40.000Z'+ )+ })+it('omits absent fields without leaving blank lines', () => {const text = formatErrorDiagnostics({ errorText: 'boom' })- expect(text).not.toContain('layer:')expect(text).not.toContain('time:')+ expect(text).not.toContain('layer:')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"@@ -199,13 +195,11 @@ 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)+describe('cron session read-only (#141348)', () => {+ it('renders its own copy and offers a new chat instead of Retry', () => {+ const surface = parseErrorSurface({ layer: 'gateway', code: 'cron_session_read_only', retryable: false })- 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(errorCardText(en.assistant.thread, surface)).toEqual(en.assistant.thread.errorCodes.cron_session_read_only)expect(errorRecoveryPlan(surface)).toMatchObject({ retry: false, startNewSession: true })})})diff --git a/apps/desktop/src/lib/error-surface.ts b/apps/desktop/src/lib/error-surface.tsindex dd54265cce2..7228ee8184a 100644--- a/apps/desktop/src/lib/error-surface.ts+++ b/apps/desktop/src/lib/error-surface.ts@@ -51,7 +51,7 @@ 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.+ // The chat is a scheduled job's session: it only runs that job, so a typed message never runs there.'cron_session_read_only',// The owner did not confirm a forwarded send in time; it may already be queued: no Retry.'SESSION_OWNER_UNCONFIRMED',@@ -274,8 +274,8 @@ 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 },+ cron_session_read_only: { retry: false, startNewSession: true },content_policy_blocked: { editMessage: true, retry: false },context_overflow: { compress: true, retry: false, startNewSession: true },disk_full: { openHermesFolder: true, retry: true },@@ -314,8 +314,8 @@ export function errorRecoveryPlan(surface: ErrorSurface | null | undefined): Errexport function formatErrorDiagnostics(input: {appVersion?: stringerrorText: string- /** Epoch seconds when the gateway recorded the failure. Absent on legacy frames. */- failureAt?: number+ /** Epoch seconds the failure was recorded (the bubble's own time), never the copy time. */+ failedAt?: numbermodel?: stringprovider?: stringsurface?: ErrorSurface | null@@ -324,14 +324,10 @@ export function formatErrorDiagnostics(input: {// caller-supplied fallback (typically the foreground composer's atoms).const provider = input.surface?.provider || input.providerconst 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() : nullconst lines = ['── Hermes error details ──',- failureTime ? `time: ${failureTime}` : null,+ input.failedAt ? `time: ${new Date(input.failedAt * 1000).toISOString()}` : 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.tsindex 0155fb1baa0..811f61b191a 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -5615,7 +5615,6 @@ 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 | nullusage?: Usage | nullstatus?: TurnStatus | nullreasoning?: string | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 64e5cbce5d3..bf0e80e9f20 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -23466,18 +23466,6 @@"default": "","title": "Text"},- "timestamp": {- "anyOf": [- {- "type": "number"- },- {- "type": "null"- }- ],- "default": null,- "title": "Timestamp"- },"usage": {"anyOf": [{diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..1b36d1b4d2a--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1 @@+Ehsan-hashdiff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 5917d8232c0..fe9edf5be5c 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -11,7 +11,6 @@ from contextvars import ContextVarfrom dataclasses import asdict, dataclass, fieldfrom functools import partialimport sqlite3-import timefrom types import SimpleNamespaceimport uuid@@ -40,14 +39,6 @@ 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,-}-@dataclassclass LiveSession:@@ -1179,31 +1170,6 @@ 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 logginglogging.getLogger(__name__).exception('Admitted turn %s failed', row['admission_id'])diff --git a/gateway/session_cron.py b/gateway/session_cron.pyindex e3c78a25000..ddec880fd90 100644--- a/gateway/session_cron.py+++ b/gateway/session_cron.py@@ -108,6 +108,11 @@ def _create(authority, actor, params):'session_id': sid, 'route': route, 'entry': entry.to_dict(), 'policy': asdict(policy)}, request_id+# What a message typed into a scheduled job's session settles with (see ``execute``).+CRON_SESSION_READ_ONLY_TEXT = ('This chat belongs to a scheduled job and only runs that job, so your '+ 'message was not run. Start a new chat to send it.')+CRON_SESSION_READ_ONLY_SURFACE = {'layer': 'gateway', 'code': 'cron_session_read_only', 'retryable': False}+# Run-side verdicts run_job stamps on the job dict for the firing scheduler's bookkeeping tail# (cron/quota_hold.py parks past a closed usage window; cron/unreachable_retry.py re-runs a# never-reached model). They cross the authority boundary inside the cron result.@@ -234,7 +239,13 @@ async def execute(authority, ref, row, policy):if (row['payload'] != {'text': data['extra_prompt'] or ''}or row['request_id'] != data['request_id']or row['principal_id'] != authority.sessions[ref.session_id].source.user_id):- raise RuntimeStoreError('admission_conflict')+ # A cron session only runs its own frozen fire; anything else typed into it fails with a+ # descriptor the viewer can render (and offer a new chat for), never a generic failure.+ authority.pending_results[row['admission_id']] = {'result': {+ 'final_response': '', 'messages': [], 'failed': True, 'completed': False,+ 'error': CRON_SESSION_READ_ONLY_TEXT, 'error_surface': dict(CRON_SESSION_READ_ONLY_SURFACE)},+ 'usage': {}}+ return CRON_SESSION_READ_ONLY_TEXTcancellations = _cancellations(authority)cancel = cancellations.setdefault(row['admission_id'], threading.Event())execution_id = scheduler_execution_id(data['cron_job']['id'], row['request_id'])diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.pyindex 48d6a0f3ca6..bb04d7bf6f4 100644--- a/gateway/session_settlement_recovery.py+++ b/gateway/session_settlement_recovery.py@@ -1,7 +1,6 @@"""Fence an unsettled claim in a live owner without inventing a terminal result."""import asyncioimport logging-import mathimport sqlite3from hermes_state_runtime import RuntimeStoreError, _admission, _epoch, settle_steer_transfers@@ -62,22 +61,9 @@ 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 isinstance(captured_result.get('error_surface'), dict):+ # Only gateway-owned refusals set this (``session_cron.execute``); ``text`` is already their copy.+ complete['error_surface'] = captured_result['error_surface']if response and captured_result.get('response_reused'):complete['response_reused'] = Trueif captured_result.get('local_viewer'):diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex 33ba47e2446..2c4b7f2ea4d 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -220,6 +220,8 @@"assistant.thread.errorCodes.content_policy_blocked.title","assistant.thread.errorCodes.context_overflow.body","assistant.thread.errorCodes.context_overflow.title",+ "assistant.thread.errorCodes.cron_session_read_only.body",+ "assistant.thread.errorCodes.cron_session_read_only.title","assistant.thread.errorCodes.disk_full.body","assistant.thread.errorCodes.disk_full.title","assistant.thread.errorCodes.empty_response.body",diff --git a/tests/gateway/test_cron_admission_error_surface.py b/tests/gateway/test_cron_admission_error_surface.pyindex c057c195ed9..98108169765 100644--- a/tests/gateway/test_cron_admission_error_surface.py+++ b/tests/gateway/test_cron_admission_error_surface.py@@ -1,176 +1,49 @@-"""Cron admission conflicts keep a safe, actionable terminal error."""-from __future__ import annotations-+"""A message typed into a cron session fails with a renderable read-only descriptor (#141348)."""import jsonimport threading-import timefrom types import SimpleNamespaceimport 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,- }+# Import-time update recovery stats the checkout's git dir; collection runs before the home I/O guard.+import gateway.session_managed_worker+from gateway.session_authority import SessionAuthority@pytest.mark.asyncio-async def test_same_message_after_terminal_cron_admission_is_rejected_without_running_job(owner, monkeypatch):- from gateway import session_authority+async def test_typed_turn_in_cron_session_settles_with_read_only_surface(owner, monkeypatch):+ from cron import schedulerfrom gateway.config import Platformfrom gateway.session import SessionSource- from gateway.session_authority import SessionAuthorityfrom gateway.session_contract import SessionReffrom gateway.session_local import LocalSessionAdapter- from hermes_state_runtime import admit_session_input, claim_session_input, settle_session_input+ from gateway.session_results import prepare_result+ from gateway.session_settlement_recovery import completion_payload+ from hermes_state_runtime import admit_session_input, claim_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+ session_id = 'cron-session'+ owner.db.create_session(session_id, source='local')+ source = SessionSource(platform=Platform.LOCAL, chat_id=session_id, user_id='cron-user', profile='default')+ owner.sessions[session_id] = SimpleNamespace(+ source=source, review=None, event_stream=SimpleNamespace(lock=threading.RLock()), subscribers=())adapter = LocalSessionAdapter(owner)adapter.register_source(source)+ adapter.policies[session_id] = SimpleNamespace(source='cron', request_json=json.dumps(+ {'cron_job': {'id': 'job-1'}, 'extra_prompt': '', 'request_id': 'cron:job-1:fire-1'}))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', lambda *a, **k: pytest.fail('a typed turn must not run the job'))+ # The person's message, not the fire's own admission.+ admit_session_input(owner.db, epoch=owner.epoch, principal_id='desktop-user', session_id=session_id,+ request_id='typed-1', payload={'text': 'run this again now'})+ row = claim_session_input(owner.db, epoch=owner.epoch, session_id=session_id)- 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+ owner, SessionRef('default', session_id), owner.sessions[session_id], row)++ captured = owner.pending_results[row['admission_id']]+ settled_outcome, _stored = prepare_result(row, response, outcome, captured)+ assert settled_outcome == 'failed'+ complete = completion_payload(row, {'outcome': settled_outcome}, response, captured)+ assert complete['status'] == 'error'+ assert complete['error_surface'] == {'layer': 'gateway', 'code': 'cron_session_read_only', 'retryable': False}+ assert 'scheduled job' in complete['text'] and 'Start a new chat' in complete['text']diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex 6cf08104fe4..b44328f5f04 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -240,9 +240,6 @@ 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 = Noneusage: Usage | None = Nonestatus: TurnStatus | None = Nonereasoning: str | None = None