The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): key the live-owner escape off the 4090 reason code, drop the prose sniffer
Tekniumc80003ff57b1
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex 0903b4f078c..1b95bc769a2 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -32,7 +32,7 @@ import { $introSplash } from '@/store/intro-splash'import { $pinnedSessionIds } from '@/store/layout'import { $petActive } from '@/store/pet'import { $petOverlayActive } from '@/store/pet-overlay'-import { $activeGatewayProfile, $gatewaySwapTarget, $hydrationSyncProfile, $profiles, requestFreshSession } from '@/store/profile'+import { $activeGatewayProfile, $gatewaySwapTarget, $hydrationSyncProfile, $profiles } from '@/store/profile'import {$connection,$contextSuggestions,@@ -46,7 +46,6 @@ import {resolveComposerSessionKey,sessionMatchesStoredId,sessionPinId,- setResumeExhaustedSessionId,shouldMigrateComposerScope} from '@/store/session'import { $focusedStoredSessionId, sessionTileDelegate } from '@/store/session-states'@@ -706,18 +705,7 @@ const ChatViewContent = memo(function ChatViewContent({description={t.desktop.resumeStrandedBody}title={t.desktop.resumeStrandedTitle}>- <div className="flex flex-wrap items-center justify-center gap-2">- <Button- onClick={() => {- // Clear the stranded latch before minting a draft so the- // new session is not immediately covered by this overlay.- setResumeExhaustedSessionId(null)- requestFreshSession()- }}- size="sm"- >- {t.desktop.resumeStartNewSession}- </Button>+ <div className="grid justify-items-center"><Button onClick={() => onRetryResume(routedSessionId)} size="sm" variant="outline">{t.desktop.resumeRetry}</Button>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 0673798c18e..edbf615359c 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@@ -5837,3 +5837,50 @@ describe('usePromptActions reloadFromMessage failed-submit rollback (#95745)', (expect(latest?.awaitingResponse).toBe(false)})})++describe('usePromptActions live-owner refusal (#106217)', () => {+ afterEach(() => {+ cleanup()+ clearNotifications()+ })++ it('stamps the 4090 SESSION_NOT_OWNED refusal as a non-retryable gateway error surface', async () => {+ // Another surface (TUI) holds the lease: the gateway refuses prompt.submit+ // with the machine reason in error.data. The inline error bubble must+ // carry that as a structured descriptor so the card can drop Retry and+ // offer "Start new session" without sniffing the English prose.+ let latest: Record<string, unknown> | undefined++ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'prompt.submit') {+ throw new JsonRpcGatewayError(+ 'Session 20260909_095312_6b93f5 already has a live owner (tui, pid 32977, lease age 22m).',+ { code: 4090, data: { reason: 'SESSION_NOT_OWNED' } }+ )+ }++ return {} as never+ })++ let handle: HarnessHandle | null = null+ await actRender(+ <Harness+ onReady={h => (handle = h)}+ onSeedState={next => {+ latest = next+ }}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ />+ )++ expect(await handle!.submitText('continue here')).toBe(false)++ const bubble = (latest?.messages as { error?: string; errorSurface?: Record<string, unknown> }[]).at(-1)++ expect(bubble?.error).toMatch(/already has a live owner/)+ expect(bubble?.errorSurface).toEqual({ layer: 'gateway', code: 'SESSION_NOT_OWNED', retryable: false })+ // Not a stale-runtime symptom: no resume/re-mint attempt hides the refusal.+ expect(requestGateway.mock.calls.map(c => c[0])).toEqual(['prompt.submit'])+ })+})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 fc6115650b8..bea099da65b 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@@ -45,6 +45,7 @@ import {inlineErrorMessage,isProviderSetupError,isSessionBusyError,+ isSessionNotOwnedError,isTargetSessionBusy,releaseSubmitInFlight,SessionRecoveryAborted,@@ -855,6 +856,9 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {const message = inlineErrorMessage(err, copy.promptFailed)const occurredAt = Date.now() / 1000+ // Another surface owns the session (#106217): a deterministic gateway+ // refusal, so the error card drops Retry and offers a new session.+ const notOwned = isSessionNotOwnedError(err)updateSessionState(sessionId,@@ -867,6 +871,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {role: 'assistant',parts: [],error: message || copy.promptFailed,+ ...(notOwned && { errorSurface: { layer: 'gateway', code: 'SESSION_NOT_OWNED', retryable: false } }),branchGroupId: state.pendingBranchGroup ?? undefined,completedAt: occurredAt,timestamp: occurredAtdiff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.tsindex c5bfb83da70..ef315bbcc7b 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts@@ -1,4 +1,5 @@import type { AppendMessage } from '@assistant-ui/react'+import { JsonRpcGatewayError } from '@hermes/shared'import { translateNow, type Translations } from '@/i18n'import type { ChatMessage } from '@/lib/chat-messages'@@ -281,6 +282,17 @@ export function isSessionBusyError(error: unknown): boolean {return /session busy/i.test(error instanceof Error ? error.message : String(error))}+// prompt.submit refused because another surface (TUI, messaging gateway)+// holds this session's lease (4090 / SESSION_NOT_OWNED, #106217). The gateway+// stamps the machine reason in `error.data.reason`; the prose fallback covers+// backends older than that contract. Deterministic until the owner lets go —+// Retry reproduces it, so the card offers "Start new session" instead.+export function isSessionNotOwnedError(error: unknown): boolean {+ const reason = error instanceof JsonRpcGatewayError ? (error.data as { reason?: unknown } | undefined)?.reason : null++ return reason === 'SESSION_NOT_OWNED' || /already has a live owner/i.test(error instanceof Error ? error.message : '')+}+const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))// Retry a gateway call across transient "session busy" so it never reaches thediff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsxindex 3518fadffe7..4b76e5eb577 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx@@ -18,14 +18,10 @@ import { Thread } from '.'const requestFreshSession = vi.hoisted(() => vi.fn())-vi.mock('@/store/profile', async importOriginal => {- const actual = await importOriginal<typeof import('@/store/profile')>()-- return {- ...actual,- requestFreshSession: () => requestFreshSession()- }-})+vi.mock('@/store/profile', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ requestFreshSession: () => requestFreshSession()+}))// Timeline timestamps render only when `display.timestamps` is enabled.$displayTimestamps.set(true)@@ -98,7 +94,8 @@ function ownershipRefusalMessage(): ThreadMessage {unstable_annotations: [],unstable_data: [],steps: [],- custom: {}+ // What submit.ts stamps on a 4090 / SESSION_NOT_OWNED refusal.+ custom: { errorSurface: { layer: 'gateway', code: 'SESSION_NOT_OWNED', retryable: false } }}} as unknown as ThreadMessage}diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsxindex 49e7e83ef46..aa019a63ef8 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx@@ -43,7 +43,6 @@ import {XIcon} from '@/lib/icons'import { extractPreviewTargets } from '@/lib/preview-targets'-import { isSessionOwnershipRefusal } from '@/lib/session-ownership-refusal'import { markAssistantIdSpoken } from '@/lib/spoken-reply'import { useEnterAnimation } from '@/lib/use-enter-animation'import { cn } from '@/lib/utils'@@ -513,11 +512,12 @@ const ErrorRecoveryActions: FC = () => {// Retry = assistant-ui reload (same wiring as the footer's refresh action):// re-runs the failed turn's prompt in place. Suppressed when the classifier- // says the failure is deterministic (retrying reproduces it), and when the- // error is a live-owner exclusivity refusal (#106217) — Retry just hits the- // same 4090 again.- const ownershipRefusal = isSessionOwnershipRefusal(errorText)- const retryable = (!surface || surface.retryable) && !ownershipRefusal+ // says the failure is deterministic (retrying reproduces it).+ const retryable = !surface || surface.retryable++ // Another surface holds this session's lease (#106217): Retry would hit the+ // same refusal, so the way out is a fresh session on this surface.+ const ownershipRefusal = surface?.code === 'SESSION_NOT_OWNED'// Switch Provider deep-links Settings → Models for the layers where the fix// is provider/endpoint/auth config, not a retry.diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex cd265853b21..3ea949c3e64 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2962,7 +2962,6 @@ export const ar = defineLocale({resumeStrandedBody:'فشل الاتصال بهذه الجلسة وتوقفت إعادة المحاولة التلقائية. تأكد من تشغيل البوابة، ثم حاول مجددا.',resumeRetry: 'إعادة المحاولة',- resumeStartNewSession: 'بدء جلسة جديدة',nothingToBranch: 'لا يوجد ما يمكن تفريعه',branchNeedsChat: 'يحتاج التفريع إلى محادثة',sessionBusy: 'الجلسة مشغولة',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 9c48c76817b..0a6ae26a41a 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3793,7 +3793,6 @@ export const en: Translations = {resumeStrandedBody:'The connection to this session failed and automatic retries gave up. Check that the gateway is running, then try again.',resumeRetry: 'Retry',- resumeStartNewSession: 'Start new session',nothingToBranch: 'Nothing to branch',branchNeedsChat: 'Start or resume a chat before branching.',sessionBusy: 'Session busy',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 4c5af4f0ad3..92e13cc5f5d 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -3361,7 +3361,6 @@ export const ja = defineLocale({resumeStrandedBody:'このセッションへの接続に失敗し、自動再試行も停止しました。ゲートウェイが実行中か確認してから、もう一度お試しください。',resumeRetry: '再試行',- resumeStartNewSession: '新しいセッションを開始',nothingToBranch: 'ブランチするものがありません',branchNeedsChat: 'ブランチする前にチャットを開始または再開してください。',sessionBusy: 'セッションが使用中',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex bd1021966b0..2d5a5b2f625 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -3741,7 +3741,6 @@ export const ru = defineLocale({resumeStrandedBody:'Соединение с этим сеансом оборвалось, и автоматические повторные попытки исчерпаны. Проверьте, что шлюз работает, и попробуйте снова.',resumeRetry: 'Повторить',- resumeStartNewSession: 'Начать новую сессию',nothingToBranch: 'Нечего ветвить',branchNeedsChat: 'Начните или возобновите чат перед ветвлением.',sessionBusy: 'Сеанс занят',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 462149c8927..9f427d5a717 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -3287,8 +3287,6 @@ export interface Translations {resumeStrandedTitle: stringresumeStrandedBody: stringresumeRetry: string- /** Same escape as errorStartNewSession for the full-window stranded overlay (#106217). */- resumeStartNewSession: stringnothingToBranch: stringbranchNeedsChat: stringsessionBusy: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 82d263a6dc9..5376fdc77b1 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -3222,7 +3222,6 @@ export const zhHant = defineLocale({resumeStrandedTitle: '無法載入此工作階段',resumeStrandedBody: '與此工作階段的連線失敗,自動重試已停止。請確認閘道正在執行,然後重試。',resumeRetry: '重試',- resumeStartNewSession: '開始新工作階段',nothingToBranch: '沒有可分支的內容',branchNeedsChat: '分支前請先開始或繼續一個聊天。',sessionBusy: '工作階段忙碌中',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex a58c8b694ab..c82b2da9e3d 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3919,7 +3919,6 @@ export const zh: Translations = {resumeStrandedTitle: '无法加载此会话',resumeStrandedBody: '与此会话的连接失败,自动重试已停止。请确认网关正在运行,然后重试。',resumeRetry: '重试',- resumeStartNewSession: '开始新会话',nothingToBranch: '没有可分支的内容',branchNeedsChat: '分支前请先开始或恢复一个对话。',sessionBusy: '会话忙碌中',diff --git a/apps/desktop/src/lib/session-ownership-refusal.test.ts b/apps/desktop/src/lib/session-ownership-refusal.test.tsdeleted file mode 100644index 0f4d03d1128..00000000000--- a/apps/desktop/src/lib/session-ownership-refusal.test.ts+++ /dev/null@@ -1,26 +0,0 @@-import { describe, expect, it } from 'vitest'--import { isSessionOwnershipRefusal } from './session-ownership-refusal'--describe('isSessionOwnershipRefusal', () => {- it('matches the active-session exclusivity message', () => {- expect(- isSessionOwnershipRefusal(- 'Session 20260909_095312_6b93f5 already has a live owner (tui, pid 32977, lease age 22m). ' +- 'Its turn activity is unknown; an open lease does not mean a turn is running. ' +- 'Attach through a compatible owner, or close the session in its owning surface ' +- 'before resuming here. Do not delete a live owner\'s lease to force a takeover.'- )- ).toBe(true)- })-- it('matches the machine reason code', () => {- expect(isSessionOwnershipRefusal('hermes-refusal-reason: SESSION_NOT_OWNED')).toBe(true)- })-- it('ignores unrelated turn failures', () => {- expect(isSessionOwnershipRefusal('rate limit exceeded')).toBe(false)- expect(isSessionOwnershipRefusal('')).toBe(false)- expect(isSessionOwnershipRefusal(null)).toBe(false)- })-})diff --git a/apps/desktop/src/lib/session-ownership-refusal.ts b/apps/desktop/src/lib/session-ownership-refusal.tsdeleted file mode 100644index 5509256c5eb..00000000000--- a/apps/desktop/src/lib/session-ownership-refusal.ts+++ /dev/null@@ -1,23 +0,0 @@-/**- * Detect the per-session exclusivity refusal that arrives as a Desktop turn- * error (gateway JSON-RPC 4090 → inline assistant error bubble).- *- * The lease/ownership guard itself is correct; Desktop must still offer an- * escape (start a new session) because Retry only reproduces the same refusal.- * Match the stable English contract from- * `hermes_cli.active_sessions.session_already_owned_message` plus the machine- * reason code when present in diagnostics text.- */-export function isSessionOwnershipRefusal(text: string | null | undefined): boolean {- const value = (text || '').trim()- if (!value) {- return false- }-- if (/\balready has a live owner\b/i.test(value)) {- return true- }-- // Machine reason may appear in copied diagnostics or structured error dumps.- return /\bSESSION_NOT_OWNED\b/.test(value)-}