The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): unwrap Models-page code-skew 503 and recycle the owned backend (#97046)
xxxigmbcecd675f7ca
diff --git a/apps/desktop/electron/backend-recycle.test.ts b/apps/desktop/electron/backend-recycle.test.tsnew file mode 100644index 00000000000..f1681f926d8--- /dev/null+++ b/apps/desktop/electron/backend-recycle.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it, vi } from 'vitest'++import { recycleOwnedBackend, recycleOwnedBackendTarget } from './backend-recycle'++describe('recycleOwnedBackendTarget', () => {+ it('treats an empty or matching profile as the primary backend', () => {+ expect(recycleOwnedBackendTarget(undefined, 'default')).toBe('primary')+ expect(recycleOwnedBackendTarget('', 'default')).toBe('primary')+ expect(recycleOwnedBackendTarget('default', 'default')).toBe('primary')+ })++ it('treats any other named profile as a pooled backend', () => {+ expect(recycleOwnedBackendTarget('paid-ads', 'default')).toBe('pool')+ })+})++describe('recycleOwnedBackend', () => {+ it('kills the owned SSH serve before the primary child, then notifies apply', async () => {+ const events: string[] = []++ const target = await recycleOwnedBackend({+ notifyApplied: () => events.push('applied'),+ primaryProfile: 'default',+ profile: undefined,+ teardownPool: async () => {+ events.push('pool')+ },+ teardownPrimary: async () => {+ events.push('primary')+ },+ teardownSsh: async profile => {+ events.push(`ssh:${profile}`)+ }+ })++ expect(target).toBe('primary')+ expect(events).toEqual(['ssh:', 'primary', 'applied'])+ })++ it('recycles a pooled profile without tearing down the primary', async () => {+ const events: string[] = []++ const target = await recycleOwnedBackend({+ notifyApplied: () => events.push('applied'),+ primaryProfile: 'default',+ profile: 'paid-ads',+ teardownPool: async profile => {+ events.push(`pool:${profile}`)+ },+ teardownPrimary: async () => {+ events.push('primary')+ },+ teardownSsh: async profile => {+ events.push(`ssh:${profile}`)+ }+ })++ expect(target).toBe('pool')+ expect(events).toEqual(['ssh:paid-ads', 'pool:paid-ads'])+ })++ it('awaits SSH teardown before the local child even when SSH is slow', async () => {+ const events: string[] = []+ let releaseSsh!: () => void++ const sshGate = new Promise<void>(resolve => {+ releaseSsh = resolve+ })++ const run = recycleOwnedBackend({+ notifyApplied: () => events.push('applied'),+ primaryProfile: 'default',+ teardownPool: vi.fn(),+ teardownPrimary: async () => {+ events.push('primary')+ },+ teardownSsh: async () => {+ events.push('ssh-start')+ await sshGate+ events.push('ssh-done')+ }+ })++ await Promise.resolve()+ expect(events).toEqual(['ssh-start'])++ releaseSsh()+ await run++ expect(events).toEqual(['ssh-start', 'ssh-done', 'primary', 'applied'])+ })+})diff --git a/apps/desktop/electron/backend-recycle.ts b/apps/desktop/electron/backend-recycle.tsnew file mode 100644index 00000000000..ffa428734f4--- /dev/null+++ b/apps/desktop/electron/backend-recycle.ts@@ -0,0 +1,47 @@+/**+ * Recycle a Desktop-owned backend after a code-skew 503.+ *+ * Closing the local tunnel/child is not enough for SSH: `serve --isolated`+ * detaches with setsid/nohup, so a reconnect would reuse the still-alive+ * stale process via the lockfile. Kill the owned remote serve first (while+ * the SSH channel can still exec), then tear down the local child — the+ * same order as connection apply (#97046, #91668).+ */++export type RecycleOwnedBackendTarget = 'pool' | 'primary'++export interface RecycleOwnedBackendDeps {+ notifyApplied: () => void+ primaryProfile: string+ profile?: null | string+ teardownPool: (profile: string) => Promise<void>+ teardownPrimary: () => Promise<void>+ teardownSsh: (profile: string) => Promise<void>+}++export function recycleOwnedBackendTarget(+ profile: null | string | undefined,+ primaryProfile: string+): RecycleOwnedBackendTarget {+ const key = String(profile ?? '').trim()++ return !key || key === primaryProfile ? 'primary' : 'pool'+}++export async function recycleOwnedBackend(deps: RecycleOwnedBackendDeps): Promise<RecycleOwnedBackendTarget> {+ const target = recycleOwnedBackendTarget(deps.profile, deps.primaryProfile)+ const profile = String(deps.profile ?? '').trim()++ if (target === 'primary') {+ await deps.teardownSsh('')+ await deps.teardownPrimary()+ deps.notifyApplied()++ return target+ }++ await deps.teardownSsh(profile)+ await deps.teardownPool(profile)++ return target+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 64d706b5eb9..e2b76819726 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -63,6 +63,7 @@ import {verifyHermesCli} from './backend-probes'import { waitForDashboardPortAnnouncement } from './backend-ready'+import { recycleOwnedBackend } from './backend-recycle'import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate'import {isHostKeyChangedBootFailure,@@ -14482,6 +14483,21 @@ const hudIpc = registerHudIpc({}})+ipcMain.handle('hermes:backend:recycle', async (_event, profile) => {+ // Models-page recovery after a code-skew 503 (#97046): kill the owned+ // SSH serve (if any) before the local child so reconnect cannot reuse a+ // stale lockfile. Soft primary teardown keeps the renderer shell mounted.+ await recycleOwnedBackend({+ notifyApplied: sendConnectionApplied,+ primaryProfile: primaryProfileKey(),+ profile: typeof profile === 'string' ? profile : '',+ teardownPool: teardownPoolBackendAndWait,+ teardownPrimary: () => teardownPrimaryBackendAndWait({ soft: true }),+ teardownSsh: value => teardownSshConnection(value || null)+ })++ return { ok: true }+})ipcMain.handle('hermes:bootstrap:reset', async () => {// Renderer's "Reload and retry" path. Clear the latched failure and// reset connection state so the next startHermes() call restarts thediff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 9998a1176bd..b257007338e 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -475,6 +475,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {// reload mid-bootstrap.getBootstrapState: () => ipcRenderer.invoke('hermes:bootstrap:get'),continueBootstrapLocal: () => ipcRenderer.invoke('hermes:bootstrap:continue-local'),+ recycleBackend: profile => ipcRenderer.invoke('hermes:backend:recycle', profile),resetBootstrap: () => ipcRenderer.invoke('hermes:bootstrap:reset'),repairBootstrap: () => ipcRenderer.invoke('hermes:bootstrap:repair'),cancelBootstrap: () => ipcRenderer.invoke('hermes:bootstrap:cancel'),diff --git a/apps/desktop/src/app/settings/model-settings.test.tsx b/apps/desktop/src/app/settings/model-settings.test.tsxindex 97d9eb84b42..06cd8a27367 100644--- a/apps/desktop/src/app/settings/model-settings.test.tsx+++ b/apps/desktop/src/app/settings/model-settings.test.tsx@@ -593,3 +593,44 @@ describe('ModelSettings MoA preset editor', () => {}})})++describe('ModelSettings code-skew 503', () => {+ const skewError = new Error(+ 'Error invoking remote method \'hermes:api\': Error: 503: {"detail":"Restart required: This process is running code from 08b4875f4a but the checkout on disk is now 48d2528066. The model picker would risk a stale-module crash — restart the Desktop-owned backend to load the new code (use Restart backend in Hermes Desktop, or quit and reopen the app)"}'+ )++ afterEach(() => {+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+ })++ it('unwraps the stale-backend 503 instead of dumping IPC JSON', async () => {+ getGlobalModelOptions.mockRejectedValueOnce(skewError)++ await renderModelSettings()++ await waitFor(() => {+ expect(screen.getByText(/running old code after an update/i)).toBeTruthy()+ })+ expect(screen.getByRole('button', { name: 'Restart backend' })).toBeTruthy()+ expect(screen.queryByText(/hermes:api/)).toBeNull()+ expect(screen.queryByText(/systemctl/)).toBeNull()+ })++ it('recycles the Desktop-owned backend and reloads the catalog', async () => {+ const recycleBackend = vi.fn().mockResolvedValue({ ok: true })++ ;(window as unknown as { hermesDesktop: { recycleBackend: typeof recycleBackend } }).hermesDesktop = {+ recycleBackend+ }++ getGlobalModelOptions.mockRejectedValueOnce(skewError)++ await renderModelSettings()+ await waitFor(() => expect(screen.getByRole('button', { name: 'Restart backend' })).toBeTruthy())++ fireEvent.click(screen.getByRole('button', { name: 'Restart backend' }))++ await waitFor(() => expect(recycleBackend).toHaveBeenCalledWith(undefined))+ await waitFor(() => expect(getGlobalModelOptions.mock.calls.length).toBeGreaterThan(1))+ })+})diff --git a/apps/desktop/src/app/settings/model-settings.tsx b/apps/desktop/src/app/settings/model-settings.tsxindex a088aaf8bae..baed8f7d81a 100644--- a/apps/desktop/src/app/settings/model-settings.tsx+++ b/apps/desktop/src/app/settings/model-settings.tsx@@ -24,11 +24,12 @@ import type {StaleAuxAssignment} from '@/hermes'import { useI18n } from '@/i18n'+import { isCodeSkewRestartRequired } from '@/lib/code-skew-error'import { AlertTriangle, Cpu, Loader2 } from '@/lib/icons'import { DEFAULT_REASONING_EFFORT, REASONING_EFFORT_VALUES } from '@/lib/reasoning-effort'import { cn } from '@/lib/utils'import { setMainModelAssignment } from '@/store/cron-model-impact'-import { notifyError } from '@/store/notifications'+import { notifyError, readableError } from '@/store/notifications'import { startManualLocalEndpoint, startManualOnboarding, startManualProviderOAuth } from '@/store/onboarding'import { hermesConfigCacheWriter, invalidateHermesConfig, useHermesConfigRecord } from '../hooks/use-config-record'@@ -193,6 +194,8 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSettingconst m = t.settings.modelconst [loading, setLoading] = useState(true)const [error, setError] = useState('')+ const [skewRestart, setSkewRestart] = useState(false)+ const [restartingBackend, setRestartingBackend] = useState(false)const [mainModel, setMainModel] = useState<{ model: string; provider: string } | null>(null)const [providers, setProviders] = useState<ModelOptionProvider[]>([])const [selectedProvider, setSelectedProvider] = useState('')@@ -229,11 +232,21 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSetting// A's models/providers into profile B (or fire onMainModelChanged for A).const profileEpoch = useRef(0)+ const setCaughtError = useCallback(+ (err: unknown, fallback: string) => {+ const skew = isCodeSkewRestartRequired(err)+ setSkewRestart(skew)+ setError(skew ? m.restartRequired : readableError(err, fallback).message)+ },+ [m.restartRequired]+ )+const refresh = useCallback(async ({ replaceSelection = false }: { replaceSelection?: boolean } = {}) => {const epoch = profileEpoch.currentsetLoading(true)setError('')+ setSkewRestart(false)try {const [modelInfo, modelOptions, auxiliaryModels, moaModels] = await Promise.all([@@ -270,7 +283,7 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSettingvoid invalidateHermesConfig(scopeProfile)} catch (err) {if (profileEpoch.current === epoch) {- setError(err instanceof Error ? err.message : String(err))+ setCaughtError(err, m.loadFailed)}} finally {if (profileEpoch.current === epoch) {@@ -278,7 +291,7 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSetting}}},- [scopeProfile]+ [m.loadFailed, scopeProfile, setCaughtError])useEffect(() => {@@ -408,12 +421,12 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSetting}).catch(err => {if (moaSaveGeneration.current === generation) {- setError(err instanceof Error ? err.message : String(err))+ setCaughtError(err, m.loadFailed)}})}, 600)},- [scopeProfile]+ [m.loadFailed, scopeProfile, setCaughtError])const updateMoaPreset = useCallback(@@ -477,12 +490,12 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSettingsetMoa(saved)} catch (err) {- setError(err instanceof Error ? err.message : String(err))+ setCaughtError(err, m.loadFailed)} finally {setApplying(false)}},- [scopeProfile]+ [m.loadFailed, scopeProfile, setCaughtError])const auxiliaryTaskLabel = useCallback((key: string) => m.tasks[key]?.label ?? key, [m.tasks])@@ -592,11 +605,11 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSettingconst fallbackModel = refreshedRow?.models?.[0] ?? ''setSelectedModel(nextModel || fallbackModel)} catch (err) {- setError(err instanceof Error ? err.message : String(err))+ setCaughtError(err, m.loadFailed)} finally {setActivating(false)}- }, [apiKeyDraft, scopeProfile, selectedProviderRow])+ }, [apiKeyDraft, m.loadFailed, scopeProfile, selectedProviderRow, setCaughtError])// OAuth / external providers can't be activated with a pasted key — hand off// to the shared onboarding flow scoped to this provider's real sign-in. The@@ -660,11 +673,20 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSettingawait refresh()} catch (err) {- setError(err instanceof Error ? err.message : String(err))+ setCaughtError(err, m.loadFailed)} finally {setApplying(false)}- }, [onMainModelChanged, refresh, scopeProfile, selectedModel, selectedProvider, selectedProviderRow])+ }, [+ m.loadFailed,+ onMainModelChanged,+ refresh,+ scopeProfile,+ selectedModel,+ selectedProvider,+ selectedProviderRow,+ setCaughtError+ ])// Sibling of the applyMainModel endpoint passthrough (#65254): auxiliary// assignments targeting a user-defined provider must carry that provider's@@ -702,12 +724,12 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSetting)await refresh()} catch (err) {- setError(err instanceof Error ? err.message : String(err))+ setCaughtError(err, m.loadFailed)} finally {setApplying(false)}},- [endpointForProvider, mainModel, refresh, scopeProfile]+ [endpointForProvider, m.loadFailed, mainModel, refresh, scopeProfile, setCaughtError])const applyAuxiliaryDraft = useCallback(@@ -733,12 +755,12 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSettingsetEditingAuxTask(null)await refresh()} catch (err) {- setError(err instanceof Error ? err.message : String(err))+ setCaughtError(err, m.loadFailed)} finally {setApplying(false)}},- [auxDraft, endpointForProvider, refresh, scopeProfile]+ [auxDraft, endpointForProvider, m.loadFailed, refresh, scopeProfile, setCaughtError])const beginAuxiliaryEdit = useCallback(@@ -776,11 +798,26 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSettingsetSwitchStaleAux([])await refresh()} catch (err) {- setError(err instanceof Error ? err.message : String(err))+ setCaughtError(err, m.loadFailed)} finally {setApplying(false)}- }, [mainModel, refresh, scopeProfile])+ }, [m.loadFailed, mainModel, refresh, scopeProfile, setCaughtError])++ const recycleStaleBackend = useCallback(async () => {+ setRestartingBackend(true)+ setError('')+ setSkewRestart(false)++ try {+ await window.hermesDesktop?.recycleBackend?.(scopeProfile)+ await refresh({ replaceSelection: true })+ } catch (err) {+ setCaughtError(err, m.restartFailed)+ } finally {+ setRestartingBackend(false)+ }+ }, [m.restartFailed, refresh, scopeProfile, setCaughtError])if (loading && !mainModel) {return <ModelSettingsSkeleton />@@ -900,7 +937,22 @@ export function ModelSettings({ onMainModelChanged, scopeProfile }: ModelSetting)}</div>)}- {error && <div className="mt-2 text-xs text-destructive">{error}</div>}+ {error && (+ <div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-destructive">+ <span>{error}</span>+ {skewRestart && (+ <Button+ disabled={restartingBackend}+ onClick={() => void recycleStaleBackend()}+ size="sm"+ variant="textStrong"+ >+ {restartingBackend && <Loader2 className="size-3.5 animate-spin" />}+ {restartingBackend ? m.restartingBackend : m.restartBackend}+ </Button>+ )}+ </div>+ )}{switchStaleAux.length > 0 && (<div className="mt-2"><StaleAuxWarningdiff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 53c17ad4b16..b2c4fea7f4e 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -487,6 +487,7 @@ declare global {onBootProgress: (callback: (payload: DesktopBootProgress) => void) => () => voidgetBootstrapState: () => Promise<DesktopBootstrapState>continueBootstrapLocal: () => Promise<{ ok: boolean }>+ recycleBackend?: (profile?: null | string) => Promise<{ ok: boolean }>resetBootstrap: () => Promise<{ ok: boolean }>repairBootstrap: () => Promise<{ ok: boolean }>cancelBootstrap: () => Promise<{ ok: boolean; cancelled: boolean }>diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex d28ee1b6d8f..81f221ede5e 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -165,7 +165,8 @@ export const ar = defineLocale({microphonePermission: 'تم رفض إذن الميكروفون.',openaiRejectedApiKey: 'رفض OpenAI مفتاح API.',openaiRejectedApiKeyWithStatus: status => `رفض OpenAI مفتاح API (${status} invalid_api_key).`,- openaiTtsNeedsKey: 'يتطلب OpenAI TTS المفتاح VOICE_TOOLS_OPENAI_KEY أو OPENAI_API_KEY.'+ openaiTtsNeedsKey: 'يتطلب OpenAI TTS المفتاح VOICE_TOOLS_OPENAI_KEY أو OPENAI_API_KEY.',+ codeSkewRestartRequired: 'بعد التحديث ما زال هذا الخلفية يشغّل كودا قديما. أعد تشغيله لتحميل الكود الجديد.'},voice: {configureSpeechToText: 'اضبط تحويل الكلام إلى نص لاستخدام وضع الصوت.',@@ -864,6 +865,11 @@ export const ar = defineLocale({reasoning: 'الاستدلال',reasoningOff: 'إيقاف',defaultsFailed: 'فشل حفظ افتراضيات النموذج',+ loadFailed: 'تعذر تحميل النماذج',+ restartRequired: 'بعد التحديث ما زال هذا الخلفية يشغّل كودا قديما. أعد تشغيله لتحميل الكود الجديد.',+ restartBackend: 'إعادة تشغيل الخلفية',+ restartingBackend: 'جار إعادة تشغيل الخلفية...',+ restartFailed: 'تعذر إعادة تشغيل الخلفية',auxiliaryTitle: 'النماذج المساعدة',resetAllToMain: 'إعادة تعيين الكل إلى النموذج الرئيسي',auxiliaryDesc: 'تعمل المهام المساعدة على النموذج الرئيسي افتراضيا. عيّن نموذجا مخصصا لأي مهمة لتجاوز ذلك.',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 14befa8f5f3..1a1eacab30c 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -161,7 +161,8 @@ export const en: Translations = {microphonePermission: 'Microphone permission was denied.',openaiRejectedApiKey: 'OpenAI rejected the API key.',openaiRejectedApiKeyWithStatus: status => `OpenAI rejected the API key (${status} invalid_api_key).`,- openaiTtsNeedsKey: 'OpenAI TTS needs VOICE_TOOLS_OPENAI_KEY or OPENAI_API_KEY.'+ openaiTtsNeedsKey: 'OpenAI TTS needs VOICE_TOOLS_OPENAI_KEY or OPENAI_API_KEY.',+ codeSkewRestartRequired: 'This backend is running old code after an update. Restart it to load the new code.'},voice: {configureSpeechToText: 'Configure speech-to-text to use voice mode.',@@ -1090,6 +1091,11 @@ export const en: Translations = {reasoning: 'Reasoning',reasoningOff: 'Off',defaultsFailed: 'Failed to save model defaults',+ loadFailed: 'Could not load models',+ restartRequired: 'This backend is running old code after an update. Restart it to load the new code.',+ restartBackend: 'Restart backend',+ restartingBackend: 'Restarting backend...',+ restartFailed: 'Could not restart the backend',auxiliaryTitle: 'Auxiliary models',resetAllToMain: 'Reset all to main',auxiliaryDesc: 'Helper tasks run on the main model by default. Assign a dedicated model to any task to override.',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 376e80fcdc4..845b540d002 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -162,7 +162,8 @@ export const ja = defineLocale({microphonePermission: 'マイクのアクセス許可が拒否されました。',openaiRejectedApiKey: 'OpenAI が API キーを拒否しました。',openaiRejectedApiKeyWithStatus: status => `OpenAI が API キーを拒否しました (${status} invalid_api_key)。`,- openaiTtsNeedsKey: 'OpenAI TTS には VOICE_TOOLS_OPENAI_KEY または OPENAI_API_KEY が必要です。'+ openaiTtsNeedsKey: 'OpenAI TTS には VOICE_TOOLS_OPENAI_KEY または OPENAI_API_KEY が必要です。',+ codeSkewRestartRequired: 'アップデート後、このバックエンドは古いコードのままです。再起動して新しいコードを読み込んでください。'},voice: {configureSpeechToText: '音声モードを使用するには音声認識を設定してください。',@@ -996,6 +997,11 @@ export const ja = defineLocale({provider: 'プロバイダー',model: 'モデル',applying: '適用中...',+ loadFailed: 'モデルを読み込めませんでした',+ restartRequired: 'アップデート後、このバックエンドは古いコードのままです。再起動して新しいコードを読み込んでください。',+ restartBackend: 'バックエンドを再起動',+ restartingBackend: 'バックエンドを再起動中...',+ restartFailed: 'バックエンドを再起動できませんでした',auxiliaryTitle: '補助モデル',resetAllToMain: 'すべてメインにリセット',auxiliaryDesc:diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 015fa30aee5..361adbd0102 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -202,6 +202,7 @@ export interface Translations {openaiRejectedApiKey: stringopenaiRejectedApiKeyWithStatus: (status: string) => stringopenaiTtsNeedsKey: string+ codeSkewRestartRequired: string}voice: {configureSpeechToText: string@@ -948,6 +949,11 @@ export interface Translations {reasoning: stringreasoningOff: stringdefaultsFailed: string+ loadFailed: string+ restartRequired: string+ restartBackend: string+ restartingBackend: string+ restartFailed: stringauxiliaryTitle: stringresetAllToMain: stringauxiliaryDesc: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 25581871111..10b0a2b3c88 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -156,7 +156,8 @@ export const zhHant = defineLocale({microphonePermission: '麥克風權限已被拒絕。',openaiRejectedApiKey: 'OpenAI 拒絕了該 API 金鑰。',openaiRejectedApiKeyWithStatus: status => `OpenAI 拒絕了該 API 金鑰 (${status} invalid_api_key)。`,- openaiTtsNeedsKey: 'OpenAI TTS 需要 VOICE_TOOLS_OPENAI_KEY 或 OPENAI_API_KEY。'+ openaiTtsNeedsKey: 'OpenAI TTS 需要 VOICE_TOOLS_OPENAI_KEY 或 OPENAI_API_KEY。',+ codeSkewRestartRequired: '更新後此後端仍在執行舊程式碼。請重新啟動以載入新程式碼。'},voice: {configureSpeechToText: '設定語音轉文字後即可使用語音模式。',@@ -962,6 +963,11 @@ export const zhHant = defineLocale({provider: '提供方',model: '模型',applying: '套用中...',+ loadFailed: '無法載入模型',+ restartRequired: '更新後此後端仍在執行舊程式碼。請重新啟動以載入新程式碼。',+ restartBackend: '重新啟動後端',+ restartingBackend: '正在重新啟動後端...',+ restartFailed: '無法重新啟動後端',auxiliaryTitle: '輔助模型',resetAllToMain: '全部重設為主要模型',auxiliaryDesc: '輔助任務預設使用主要模型。您可以為任何任務指定專用模型。',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex c646707b6c0..c151641964a 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -156,7 +156,8 @@ export const zh: Translations = {microphonePermission: '麦克风权限已被拒绝。',openaiRejectedApiKey: 'OpenAI 拒绝了该 API key。',openaiRejectedApiKeyWithStatus: status => `OpenAI 拒绝了该 API key (${status} invalid_api_key)。`,- openaiTtsNeedsKey: 'OpenAI TTS 需要 VOICE_TOOLS_OPENAI_KEY 或 OPENAI_API_KEY。'+ openaiTtsNeedsKey: 'OpenAI TTS 需要 VOICE_TOOLS_OPENAI_KEY 或 OPENAI_API_KEY。',+ codeSkewRestartRequired: '更新后此后端仍在运行旧代码。请重启以加载新代码。'},voice: {configureSpeechToText: '配置语音转文字后即可使用语音模式。',@@ -1284,6 +1285,11 @@ export const zh: Translations = {reasoning: '推理',reasoningOff: '关闭',defaultsFailed: '保存模型默认值失败',+ loadFailed: '无法加载模型',+ restartRequired: '更新后此后端仍在运行旧代码。请重启以加载新代码。',+ restartBackend: '重启后端',+ restartingBackend: '正在重启后端...',+ restartFailed: '无法重启后端',auxiliaryTitle: '辅助模型',resetAllToMain: '全部重置为主模型',auxiliaryDesc: '辅助任务默认使用主模型。你可以为任意任务指定专用模型。',diff --git a/apps/desktop/src/lib/code-skew-error.test.ts b/apps/desktop/src/lib/code-skew-error.test.tsnew file mode 100644index 00000000000..32bf8d668b5--- /dev/null+++ b/apps/desktop/src/lib/code-skew-error.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest'++import { isCodeSkewRestartRequired } from './code-skew-error'++const SKEW_IPC =+ 'Error invoking remote method \'hermes:api\': Error: 503: {"detail":"Restart required: This process is running code from 08b4875f4a but the checkout on disk is now 48d2528066. The model picker would risk a stale-module crash — restart the Desktop-owned backend to load the new code (use Restart backend in Hermes Desktop, or quit and reopen the app)"}'++describe('isCodeSkewRestartRequired', () => {+ it('detects the Models-page IPC 503 from a stale Desktop-owned backend', () => {+ expect(isCodeSkewRestartRequired(new Error(SKEW_IPC))).toBe(true)+ })++ it('detects a bare FastAPI detail string', () => {+ expect(isCodeSkewRestartRequired('Restart required: checkout drifted')).toBe(true)+ })++ it('ignores unrelated 503s and load failures', () => {+ expect(isCodeSkewRestartRequired(new Error('503: Service Unavailable'))).toBe(false)+ expect(isCodeSkewRestartRequired(new Error('Failed to load models'))).toBe(false)+ expect(isCodeSkewRestartRequired(null)).toBe(false)+ })+})diff --git a/apps/desktop/src/lib/code-skew-error.ts b/apps/desktop/src/lib/code-skew-error.tsnew file mode 100644index 00000000000..f8f0268ff21--- /dev/null+++ b/apps/desktop/src/lib/code-skew-error.ts@@ -0,0 +1,12 @@+/** True when a backend error is the post-update stale-module 503 (#97046). */+export function isCodeSkewRestartRequired(error: unknown): boolean {+ return /Restart required:/i.test(errorText(error))+}++function errorText(error: unknown): string {+ if (error instanceof Error) {+ return error.message+ }++ return typeof error === 'string' ? error : String(error ?? '')+}diff --git a/apps/desktop/src/store/notifications.test.ts b/apps/desktop/src/store/notifications.test.tsindex e11ed82b4ca..c33860e4a49 100644--- a/apps/desktop/src/store/notifications.test.ts+++ b/apps/desktop/src/store/notifications.test.ts@@ -55,3 +55,16 @@ test('session storage write failure is treated as disk-full class', () => {expect(lastMessage()).toMatch(/Disk full/i)})++test('code-skew 503 unwraps to a restart-required summary, not raw IPC JSON', () => {+ notifyError(+ new Error(+ 'Error invoking remote method \'hermes:api\': Error: 503: {"detail":"Restart required: This process is running code from 08b4875f4a but the checkout on disk is now 48d2528066."}'+ ),+ 'Could not load models'+ )++ expect(lastMessage()).toMatch(/running old code after an update/i)+ expect(lastMessage()).not.toMatch(/hermes:api/)+ expect(lastMessage()).not.toMatch(/systemctl/)+})diff --git a/apps/desktop/src/store/notifications.ts b/apps/desktop/src/store/notifications.tsindex 50b3f36b546..919c5cade20 100644--- a/apps/desktop/src/store/notifications.ts+++ b/apps/desktop/src/store/notifications.ts@@ -129,6 +129,10 @@ const ERROR_SUMMARIES: { test: (msg: string) => boolean; summarize: (msg: string{test: msg => /microphone permission/i.test(msg),summarize: () => translateNow('notifications.errors.microphonePermission')+ },+ {+ test: msg => /Restart required:/i.test(msg),+ summarize: () => translateNow('notifications.errors.codeSkewRestartRequired')}]